I have following code:
foreach($foo as $n=>$ia) {
foreach($ia as $i=>$v) {
$bar[$i]->$n = $v; //here I have 'Creating default object...' warning
}
}
If I add:
$bar[$i] = new stdClass;
$bar[$i]->$n = $v;
to fix it. Then values in objects in array ‘bar’ not sets. For example, I have array:
$foo = array(
"somefield" => array("value1", "value2", "value3"),
"anotherfield" => array("value1", "value2", "value3")
);
On output I should get:
$bar[0]->somefield = value1
$bar[1]->anotherfield = value2
But in practice I get:
$bar[0]->somefield = null //(not set)
$bar[1]->anotherfield = null //too
How should I update the code to get it work?
Problem:
The problem with your code is, that if you use the first attempt,
a default empty object will be created for if you use the
->operator on a non existent array index. (NULL). You’ll get a warning as this is a bad coding practice.The second attempt
will simply fail as you overwrite
$bar[$i]each loop.Btw the code above won’t work even with PHP5.3
Solution:
I would prefer the following code example because:
$barexplicitely as emptyarray()and to create the objects using:new StdClass().code: