1

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.

2
  • Because in the other foreach you do not set "joe" as value for $result['profile_pic'] Commented Dec 16, 2016 at 11:59
  • 1
    You need to use reference operator & to reflect the changes made to the array elements. foreach($formatted_results as &$result) makes it work. Commented Dec 16, 2016 at 12:01

2 Answers 2

5

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
}

foreach - Pass by reference

Sign up to request clarification or add additional context in comments.

2 Comments

Perfect, thank you (you answered so fast stackoverflow is making me wait before I set it as the answer) But care to explain to me what the & does exactly? And in which cases shoudl I use it?
@JoeYahchouchi please go through - php.net/manual/en/language.references.php
3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.