Reputation: 626
I have this very very basic code
foreach ($formatted_results as $result) {
$result['profile_pic']="joe";//set all values to joe
var_dump( $result['profile_pic']);//prints joe
}
foreach ($formatted_results as $result) {
var_dump( $result['profile_pic']);//does not print joe!
}
where formatted_results is an array containing other arrays. Now as you can see, I am modifying in the first loop the value of every array within formatted_results to contain the name joe, and then I am printing that to make sure and sure enough, the print of the first loop returns "joe"
However, the value I set is not persisting somehow, as when I loop that same array again to check the inner values of its own arrays, it gives me the old value.
The code is exactly as I am displaying it here, there is nothing in between. I am guessing there is something about pointers that is eluding me here.
Upvotes: 1
Views: 88
Reputation: 31749
The value is not set to the actual array
, rather assigned to the current element which is not available outside the loop. You need to set the value to the actual array
you are looping through. Try -
foreach ($formatted_results as &$result) {
$result['profile_pic']="joe";//set all values to joe
}
Upvotes: 5
Reputation: 18577
Here is the code :
foreach ($formatted_results as $k => $result) {
$formatted_results[$k]['profile_pic']="joe";//set all values to joe
var_dump( $formatted_results[$k]['profile_pic']);//prints joe
}
foreach ($formatted_results as $result) {
var_dump( $result['profile_pic']);//does not print joe!
}
$result is not gonna save data to $formatted_results
Upvotes: 3