Hi,
I've got a class in PHP with an array of objects in it.
I need to loop through these objects and call 2 methods on them but I'm not sure of the best approach.
When dealing with arrays, if you use foreach, you can't seem to update the actual array. Example:
$foo = array ("first","second","third");
$x=1;
print_r ($foo);
foreach ($foo as $current){
$current = $x++;
}
print_r ($foo);
outputs the following:
Array
(
[0] => first
[1] => second
[2] => third
)
Array
(
[0] => first
[1] => second
[2] => third
)
so if $foo contains objects and not simply strings, if I call a method in that object which sets some property, as soon as the foreach moves to the next object in the array that change will be destroyed. This is pointless.
I have devised a possible solution to this as per the below:
$foo = array ("first","second","third");
$x=1;
print_r ($foo);
foreach ($foo as $current => $randomUselessVariable){
$foo[$current] = $x++;
}
print_r ($foo);
this has the desired output:
Array
(
[0] => first
[1] => second
[2] => third
)
Array
(
[0] => 1
[1] => 2
[2] => 3
)
It does however bother me a little that $randomUselessVariable is being created for no good reason and if the object happened to be a large one it might slow down the execution quite badly.
Everything I've found by searching suggests using foreach ($values as $value)
and the examples are always a simple getFoo() method and never something that updates the actual value in the array.
Has anyone got a nice happy solution to this or should I just stick with my ugly foreach ($key => $completeWasteOfResources)
?
Thanks for taking the time to read :)