Very Weird PHP is overwriting variable assignment with 1 - php

Anybody got a clue what's going on here?
Let's take this very simple piece of code:
$p_id = array();
foreach($opp->participants as $party) {
echo "ID value from data:" . var_dump($party->id) . "<br>";
echo "Base array:" . var_dump($p_id) . "<br>";
$p_uuid = array();
$p_assignment_id = array();
$p_id = array_push($p_id, "$party->id");
echo "Dump array result:" .var_dump($p_id) . "<br>";
}
This is the output I'm getting from this (Yes, that's the formatting of the output too):
int(295) ID value from data:<br>
array(0) { } Base array:<br>
int(1) Dump array result:<br>
int(298) ID value from data:<br>
array(0) { } Base array:<br>
int(1) Dump array result:<br>
int(301) ID value from data:<br>
array(0) { } Base array:<br>
int(1) Dump array result:<br>
This is obviously a noob question, but I honestly have no idea why the output looks like this.
if I use print_r, this is the result I get:
295 ID value from data:1<br>
Array ( ) Base array: 1<br>
1 Dump array result: 1<br>
298 ID value from data:1<br>
Array ( ) Base array: 1<br>
1 Dump array result: 1<br>
301 ID value from data:1<br>
Array ( ) Base array: 1<br>
1 Dump array result: 1<br>
What I'm expecting to see is an array of the ID values from $party->id, so a print_r of $p_id should result something like Array(295, 298, 301).
Instead the result is 1. Not array(1). Just 1.
For even more clarity, the data this is pulling in doesn't even have 1 as an id. So it shouldn't even exist.
I've included the print_r, and var_dump results, so you can see the raw debug output.

You do not need to assign the result of the array_push() to $p_id. As per PHP documentation the return value of an array_push() function is the new number of elements in the array and not the array itself. See here
Change the code to :
array_push($p_id, "$party->id");
That should do it.

Related

trying to get an element from an array in php

i have an array after convert it from xml data and i have var_dump the data in array like :
object(SimpleXMLElement)#651 (1) {
["authenticationSuccess"]=>
object(SimpleXMLElement)#652 (1) {
["user"]=>
string(9) "yassine"
}
}
i want to get the value the attribut user that equal "yassine" in this cas .
i trying
$xml["authenticationSuccess"]["user"]
but not working , it return null value , is there any solution to get this data from the array .
some help please
It seems your variable is not array but object, so you need to use $xml->authenticationSuccess->user;
As the var_dump says, you have an object instead of an associative array. You can access object fields like this:
$xml->authenticationSuccess->user;
or this:
$xml->{"authenticationSuccess"}->{"user"};

Cleaner way to echo multi dimension array

echo "{$line['text_1']}";
the above echo works fine ,however when it comes to 2d array, in my sublime, only {$line['text_2']} this part work fine. output error both sublime and browser
echo "$array_2d[{$line['text_1']}][{$line['text_2']}]";
any idea?
update
echo "$array_2d[$line['text_1']][$line['text_2']]";
using xampp, error Parse error: syntax error, unexpected '[', expecting ']' in C:\xampp\htdocs
and I'm just outputting a value from the mysql_fetch_assoc. I can do it in another way by echo '' however I'm trying to make my code easier for future editting and code copy paste
and yes I'm doing things like
echo "The price is $array_2d[$line['text_1']][$line['text_2']]"
with lots of html code in the double quote.
Why are you trying to output the array?
if it is for debugging purposes, you can just use the native php functions print_r() or var_dump()
You should be able to say
echo "item is {$array_2d[$line['text1']][$line['text2']]}";
to get to a subelement.
Of course, this is only really useful when it's not the only thing in the string. If you're only echoing the one value, you don't need the quotes, and things get simpler.
echo $array_2d[$line['text1']][$line['text2']];
this should work :
echo $array_2d[$line['text_1']][$line['text_2']];
When echoing variables, you don't have to use the quotes:
echo $array_2d[$line['text_1']][$line['text_2']];
If you do need to output something with that string, the concatentation operator can help you:
echo "Array: " . echo $array_2d[$line['text_1']][$line['text_2']];
You can use print_r() to echo the array.
e.g.:
print_r($array);
Output will be:
Array ( [test] => 1 [test2] => 2 [multi] => Array ( [multi] => 1 [multi2] => 2 ) )
Also you can use this to make it more readable in a HTML context:
echo '<pre>';
print_r($array);
echo '</pre>';
Output will be:
Array
(
[test] => 1
[test2] => 2
[multi] => Array
(
[multi] => 1
[multi2] => 2
)
)
You can use print_r() or var_dump() to echo an array.
The print_r() displays information about a variable in a way that's readable by humans whereas the var_dump() function displays structured information about variables/expressions including its type and value.
$array = 'YOUR ARRAY';
echo "<pre>";
print_r($array);
echo "</pre>";
or
$array = 'YOUR ARRAY';
var_dump($array);
Example variations
I'm wondering why you would try using the $line array as a key to access data in $array_2d.
Anyway, try this:
echo($line['text_1'].'<br>');
this:
echo($array_2d['text_1']['text_2'].'<br>');
and finally this (based on your "the $line array provides the keys for the $array_2d" array example)
$key_a = $line['text_1'];
$key_b = $line['text_2'];
echo($array_2d[$key_a][$key_b].'<br>');
Which can also be written shorter like this:
echo($array_2d[$line['text_1']][$line['text_2']].'<br>');
Verifying/Dumping the array contents
To verify if your arrays hold the data you expect, do not use print_r. Do use var_dump instead as it will return more information you can use to check on any issues you think you might be having.
Example:
echo('<pre>');
var_dump($array_2d);
echo('</pre>');
Differences between var_dump and print_r
The var_dump function displays structured information of a variable (or expression), including its type and value. Arrays are explored recursively with values indented to show structure. var_dump also shows which array values and object properties are references.
print_r on the other hand displays information about a variable in a readable way and array values will be presented in a format that shows keys and elements. But you'll miss out on the details var_dump provides.
Example:
$array = array('test', 1, array('two', 'more'));
output of print_r:
Array
(
[0] => test
[1] => 1
[2] => Array
(
[0] => two
[1] => more
)
)
output of var_dump:
array(3) {
[0]=> string(4) "test"
[1]=> int(1)
[2]=> array(2)
{
[0]=> string(3) "two"
[1]=> string(4) "more"
}
}

Undefined offset while accessing array element which exists

I have an array and PHP and when I print it out I can see the values I need to access, but when I try accessing them by their key I am getting a PHP Notice. I printed the array with print_r:
Array
(
[207] => sdf
[210] => sdf
)
When I try to access the array using the index I get an undefined offset notice. Here is my code:
print_r($output);
echo $output[207]; // Undefined Offset
echo $output["207"]; // Undefined Offset
The $output array is the result of a call to array_diff_key and is input originally as JSON through an HTTP POST request.
array_keys gives me the following:
Array
(
[0] => 207
[1] => 210
)
In response to the comments:
var_dump(key($output)); outputs:
string(3) "207"
var_dump(isset($output[key($output)])); outputs:
bool(false)
See this section on converting an object to an array in the PHP Manual:
The keys are the member variable names, with a few notable exceptions: integer properties are unaccessible; private variables have the class name prepended to the variable name; protected variables have a '*' prepended to the variable name.
When converting to an array from an object in PHP, integer array keys are stored internally as strings. When you access array elements in PHP or use an array normally, keys that contain valid integers will be converted to integers automatically. An integer stored internally as a string is an inaccessible key.
Note the difference:
$x = (array)json_decode('{"207":"test"}');
var_dump(key($x)); // string(3) "207"
var_dump($x);
// array(1) {
// ["207"]=>
// string(4) "test"
// }
$y['207'] = 'test';
var_dump(key($y)); // int(207)
var_dump($y);
// array(1) {
// [207]=>
// string(4) "test"
// }
print_r on both those arrays gives identical output, but with var_dump you can see the differences.
Here is some code that reproduces your exact problem:
$output = (array)json_decode('{"207":"sdf","210":"sdf"}');
print_r($output);
echo $output[207];
echo $output["207"];
And the simple fix is to pass in true to json_decode for the optional assoc argument, to specify that you want an array not an object:
$output = json_decode('{"207":"sdf","210":"sdf"}', true);
print_r($output);
echo $output[207];
echo $output["207"];
The problem arises when casting to array an object that has string keys that are valid integers.
If you have this object:
object(stdClass)#1 (2) {
["207"]=>
string(3) "sdf"
["210"]=>
string(3) "sdf"
}
and you cast it with
$array = (array)$object
you get this array
array(2) {
["207"]=>
string(3) "sdf"
["210"]=>
string(3) "sdf"
}
which has keys that can only be accessed by looping through them, since a direct access like $array["207"] will always be converted to $array[207], which does not exist.
Since you are getting an object like the one above from json_decode() applied to a string like
$json = '{"207":"sdf", "210":"sdf"}'
The best solution would be to avoid numeric keys in the first place. These are probably better modelled as numeric properties of an array of objects:
$json = '[{"numAttr":207, "strAttr":"sdf"}, {"numAttr":210, "strAttr":"sdf"}]'
This data structure has several advantages over the present one:
it better reflects the original data, as a collection of objects
which have a numeric property
it is readily extensible with other properties
it is more portable across different systems
(as you see, your current data structure is causing issues in PHP, but if you
should happen to use another language you may easily encounter
similar issues).
If a property → object map is needed, it can be quickly obtained, e.g., like this:
function getNumAttr($obj) { return $obj->numAttr; } // for backward compatibility
$arr = json_decode($json); // where $json = '[{"numAttr":...
$map = array_combine(array_map('getNumAttr', $arr), $arr);
The other solution would be to do as ascii-lime suggested: force json_decode() to output associative arrays instead of objects, by setting its second parameter to true:
$map = json_decode($json, true);
For your input data this produces directly
array(2) {
[207]=>
string(3) "sdf"
[210]=>
string(3) "sdf"
}
Note that the keys of the array are now integers instead of strings.
I would consider changing the JSON data structure a much cleaner solution, though, although I understand that it might not be possible to do so.
I've just found this bug which causes array elements to be inaccessible sometimes in PHP when the array is created by a call to unserialize.
Create a test PHP file containing (or run from the command line) the following script:
<?php
$a = unserialize('a:2:{s:2:"10";i:1;s:2:"01";i:2;}');
print $a['10']."\n";
$a['10'] = 3;
$a['01'] = 4;
print_r($a);
foreach ($a as $k => $v)
{
print 'KEY: ';
var_dump($k);
print 'VAL: ';
var_dump($v);
print "\n";
}
If you get errors you have a version of PHP with this bug in it and I recommend upgrading to PHP 5.3
Try
var_dump($output);
foreach ($output as $key => val) {
var_dump($key);
var_dump($val);
}
to learn more on what is happening.
What exact line/statement is throwing you a warning?
How did you print the array? I would suggest print_r($arrayName);
Next, you can print individual elements like: echo $arrayName[0];
Try use my approach:
class ObjectToArray {
public static function convert( $object ) {
if( !is_object( $object ) && !is_array( $object ) ) {
return $object;
}
if( is_object( $object ) ) {
$object = get_object_vars( $object );
}
return array_map( 'ObjectToArray::convert', $object );
}
}
$aNewArray = ObjectToArray::convert($oYourObject);
Just put error_reporting(0); in you method or at start of file. It will solved your issue.

Why a loop over MySQL query change an array which has nothing to do with the query?

I have the following piece of code:
print_r($queries);
$id2query = array();
while ($res_array = mysql_fetch_array($results)) {
$id = $res_array['id'];
$query = $res_array['query'];
$id2query[$id] = $query;
}
print_r($queries);
The interesting thing is that printr_r before and after the loop return different things.
Does anybody know how it can be possible?
ADDED
$queries is an array. It shown code is a part of a function and $queries is one of the arguments of the function. Before the loop it returns:
Array ( [0] => )
and after the loop it returns:
Array ( [0] => web 2.0 )
ADDED 2
web 2.0 comes from $res_array. Here is the content of the $res_array:
Array ( [0] => 17 [id] => 17 [1] => web 2.0 [query] => web 2.0 [2]
But I do not understand how a value from $res_array migrates to $queries.
ADDED 3
I tried
print "AAAA".var_dump($queries)."BBB";
it returns AAABBB.
ADDED 4
I have managed to use var_dump in the correct way and this is what it returns before the loop:
array(1) { [0]=> &string(0) "" }
This is what I have after the loop:
array(1) { [0]=> &string(7) "web 2.0" }
But I do not understand what it means.
The var_dump below ADDED 4 shows it, the array contains a reference to a string. So it is not a copy of that string, it is something like a pointer (I know, they are not real pointers, see PHPDocs below) to the original string. So if that one gets changed, the references shows the changed value too.
I'd suggest you have a look at:
PHPDoc References
PHPDoc What references do
Example code:
$s = "lulu";
$a = array(&$s);
var_dump($a);
$s = "lala";
var_dump($a);
First var_dump will return:
array(1) {
[0]=>
&string(4) "lulu"
}
And the second:
array(1) {
[0]=>
&string(4) "lala"
}

getting a value from the array in php

when i say
var_dump($this->variables['DEFAULTS_VALUES']);
I get the Following array
array(1) {
["ABE LOB RPT"]=>
string(8) "BEST2"
}
how do i get the value ["ABE BBB CCC"] from this array
when i say in this way $this->variables['DEFAULTS_VALUES'][0]
It says UNDEFINED OFFSET: 0 .how do i get the value ["ABE BBB CCC"] from this array
You're getting "undefined offset" errors because there's no value at index 0 in that array. PHP arrays are actually "ordered maps", and what looks like the first value here is actually a key -- $this->variables['DEFAULTS_VALUES']['ABE LOB RPT'] would give you back 'BEST2'.
If you actually want the keys, the array_keys function would give them to you. Or you could use a foreach loop:
foreach ($this->variables['DEFAULTS_VALUES'] as $key => $value)
{
print "$key: $value<br>\n";
}
In your case, the one and only time through the loop would print out "ABE LOB RPT: BEST2".
Your array is associative array you need this:
echo $this->variables['DEFAULTS_VALUES']['ABE LOB RPT']; // BEST2

Categories