Hyphen in Array keys - php

All,
I have an array with hyphens in the key name. How do I extract the value of it in PHP? It returns a 0 to me, if I access like this:
print $testarray->test-key;
This is how the array looks like
testarray[] = {["test-key"]=2,["hotlink"]=1}
Thanks

You have problems:
testarray[] = {["test-key"]=2,["hotlink"]=1}
1 2
You are missing $ used to create variables in php
It is not a valid array format
.
print $testarray->test-key;
1
The => operator is used for objects, not arrays, use [] instead.
Here is how your code should be like:
$testarray = array("test-key" => 2, "hotlink" => 1);
print $testarray['test-key'];
Finally,
See PHP Array Manual

print $testarray["test-key"];
The PHP manual has a good page explaining arrays and how to do things with them:
http://www.php.net/manual/en/language.types.array.php

Related

Zero in increment array started at 1

This is my code, it's for have an array :
$zi = '1';
for ($zi = 1; $zi <= $v['Store']['stock']; $zi++) {
$options_array[$zi]= $zi;
}
var_dump($options_array);
Array
(
[0] => 0
[1] => 1
[2] => 2
)
why i have the zero in my result ?
i put $zi at 1, so why ?
As my comment turned out to be correct: The issue is that you already have a property 0 in the $options_array before you even get to the presented code block. You can start with a fresh array using $options_array = [] or $options_array = array() (for older php versions). You can also just remove property 0 with unset($options_array[0]).
In php there are two kinds of arrays, numerically indexed arrays, and associative arrays. Your output seems a little suspect but I can tell you that if all the keys of a PHP array are numeric then the array will be zero based.
I see how you have $zi = '1' above, which is along the lines of what you would have to do to create a one based array, but it would be associative, and you won't be able to simply use the ++ operator. I believe even if you use a string that is a number PHP will still convert to a numerically indexed array. I recommend against trying to implement a one based array, it's insanity.
Hope this page helps http://us2.php.net/manual/en/language.types.array.php
You start setting $options_array at index 1, so index 0 is whatever the default value of the underlying type is. In this case, it's an integer, so the default is 0.

php difference between pack() and unpack()

in php 4.4.4 having:
$hbc=pack("LL",82603088,82602992);
list($v1,$v2)=unpack("L2",$hbc);
echo("v1=".$v1." v2=".$v2);
result is:
v1= v2=82603088
I already have some hours wrapping my head aroud this...
thanks
The error is not withing the pack or unpack, but inside the list().
Turn on notices! Your code will complain like this:
Notice: Undefined offset: 0 in ...
That should make you wonder. If you dump the array that is returned by unpack, it is correct:
array(2) {
[1] =>
int(82603088)
[2] =>
int(82602992)
}
And then there is this tiny little note on the docs page of list():
list() only works on numerical arrays and assumes the numerical indices start at 0.
Your array does not start at index 0, and the notice likes to tell you that.
The quick fix is:
list(,$v1,$v2)=unpack("L2",$hbc); // add a comma to skip index 0
A better approach might be to use unpack to create named array indices:
$unpacked = unpack("L2v/",$hbc);
Result:
array(2) {
'v1' =>
int(82603088)
'v2' =>
int(82602992)
}
From the php.net comments.
$int_list = array_merge(unpack("s*", $some_binary_data));
This will essentially reset your index keys starting at 0.

PHP Array to JSON Array using json_encode(); [duplicate]

This question already has answers here:
How to reindex an array?
(6 answers)
Closed 1 year ago.
I've encoded an Array I've made using the inbuilt json_encode(); function. I need it in the format of an Array of Arrays like so:
[["Afghanistan",32,12],["Albania",32,12]]
However, it is returning as:
{"2":["Afghanistan",32,12],"4":["Albania",32,12]}
How can I remove these row numbers without using any Regex trickery?
If the array keys in your PHP array are not consecutive numbers, json_encode() must make the other construct an object since JavaScript arrays are always consecutively numerically indexed.
Use array_values() on the outer structure in PHP to discard the original array keys and replace them with zero-based consecutive numbering:
Example:
// Non-consecutive 3number keys are OK for PHP
// but not for a JavaScript array
$array = array(
2 => array("Afghanistan", 32, 13),
4 => array("Albania", 32, 12)
);
// array_values() removes the original keys and replaces
// with plain consecutive numbers
$out = array_values($array);
json_encode($out);
// [["Afghanistan", 32, 13], ["Albania", 32, 12]]
json_encode() function will help you to encode array to JSON in php.
if you will use just json_encode function directly without any specific option, it will return an array.
Like mention above question
$array = array(
2 => array("Afghanistan",32,13),
4 => array("Albania",32,12)
);
$out = array_values($array);
json_encode($out);
// [["Afghanistan",32,13],["Albania",32,12]]
Since you are trying to convert Array to JSON, Then I would suggest to use JSON_FORCE_OBJECT as additional option(parameters) in json_encode, Like below
<?php
$array=['apple','orange','banana','strawberry'];
echo json_encode($array, JSON_FORCE_OBJECT);
// {"0":"apple","1":"orange","2":"banana","3":"strawberry"}
?>
I want to add to Michael Berkowski's answer that this can also happen if the array's order is reversed, in which case it's a bit trickier to observe the issue, because in the json object, the order will be ordered ascending.
For example:
[
3 => 'a',
2 => 'b',
1 => 'c',
0 => 'd'
]
Will return:
{
0: 'd',
1: 'c',
2: 'b',
3: 'a'
}
So the solution in this case, is to use array_reverse before encoding it to json
I had a problem with accented characters when converting a PHP array to JSON. I put UTF-8 stuff all over the place but nothing solved my problem until I added this piece of code in my PHP while loop where I was pushing the array:
$es_words[] = array(utf8_encode("$word"),"$alpha","$audio");
It was only the '$word' variable that was giving a problem. Afterwards it did a jason_encode no problem.
Hope that helps

An array is ending with a character(")") inside array element value, not with actual array end

An array which is populated it's value from database. when I print_r the array . It shows like below...
Array
(
[term] => These are following selection a) new b) old
)
Here the array is ending with character ) inside the term element " ..selection a) new ..", while it's only a character in the array. So How I would avoid the ending of array with charcters present inside the array ?
What you're viewing is the output of an array with print_r.
Defining an array in PHP is a little different:
$variable = array('inside First a) new, b) old');
print_r($variable);
var_dump($variable); // similar to print_r
There is also another way of doing that:
$variable = array();
$variable[0] = 'inside First a) new, b) old';
So you need to quote your value to get a string.
The array value in your declaration should be a string:
$myArray = array(
0 => 'inside First a) new , b) old';
);
In PHP you need to quote string values:
$array = array(
0 => 'inside First a) new , b) old'
);
See the manual. To be honest this is pretty basic stuff. If you don't know this, I'd suggest going away and getting a basic introduction to PHP book and reading through it...

php array processing question

Before I write my own function to do it, is there any built-in function, or simple one-liner to convert:
Array
(
[0] => pg_response_type=D
[1] => pg_response_code=U51
[2] => pg_response_description=MERCHANT STATUS
[3] => pg_trace_number=477DD76B-B608-4318-882A-67C051A636A6
)
Into:
Array
(
[pg_response_type] => D
[pg_response_code] =>U51
[pg_response_description] =>MERCHANT STATUS
[pg_trace_number] =>477DD76B-B608-4318-882A-67C051A636A6
)
Just trying to avoid reinventing the wheel. I can always loop through it and use explode.
I can always loop through it and use explode.
that's what you should do.
Edit - didn't read the question right at all, whoops..
A foreach through the array is the quickest way to do this, e.g.
foreach($arr as $key=>$val)
{
$new_vals = explode("=", $val);
$new_arr[$new_vals[0]] = $new_vals[1];
}
This should be around five lines of code. Been a while since I've done PHP but here's some pseudocode
foreach element in the array
explode result on the equals sign, set limit = 2
assign that key/value pair into a new array.
Of course, this breaks on keys that have more than one equals sign, so it's up to you whether you want to allow keys to have equals signs in them.
You could do it like this:
$foo = array(
'pg_response_type=D',
'pg_response_code=U51',
'pg_response_description=MERCHANT STATUS',
'pg_trace_number=477DD76B-B608-4318-882A-67C051A636A6',
);
parse_str(implode('&', $foo), $foo);
var_dump($foo);
Just be sure to encapsulate this code in a function whose name conveys the intent.

Categories