This question already has an answer here:
I have this following code:
foreach ($animals as $animal) { $animal = getOffSpring($animal); }
Since I am setting $animal to a new string, will I be modifying the array as well please?
My run suggests that my array remains the same, but I want it to be modified with the new value. Is this the bug?
In other words, I want all the animals within my array to be modified to their offsprings
</div>
You can use a reference:
foreach ($animals as &$animal) {
$animal = getOffSpring($animal);
}
unset($animal);
The unset
after the loop clears the reference. Otherwise you keep a reference to the last array element in $animal
after the loop which will cause annoying problems if you forget about this and then use $animal
later for something else.
Another option would be using the key to replace it:
foreach ($animals as $key => $animal) {
$animals[$key] = getOffSpring($animal);
}
I think you are trying to do that.
When you take $animal
variable and pass it to a function or modifie it inside foreach
loop, you work with independent variable, that isn't linked to $animals
array in any way ( if you don't link it yourself ), therefore all changes applied to it, don't result in modification of $animals
array.
foreach ( $animals as $i => $animal )
{
$animals[ $i ] = getOffSpring( $animal );
}
As @AlecTMH mentioned in his comment, array_map
is also a solution.
array_map( 'getOffSpring', $animals );
You can use a reference to the value in the array
foreach ($animals as &$animal) {
$animal = getOffSpring($animal);
}