0

I have an array called $my_array . I created $my_array like this:

 $my_array = [];
 $my_array[0] = [];
 $my_array[1] = [];
 $my_array[2] = [];
 $my_array[3] = [];

Each element of $my_array is an array:

foreach ($my_array as $array){
    print(gettype($array));
    print(" ///   ");
}

output: array /// array /// array /// array ///

foreach ($my_array as $array){


    $array['link_root'] = "a string";

    print($array['link_root']);
    print("     /////     ");
}

output is: a string ///// a string ///// a string ///// a string /////

and then when I try:

print($my_array[0]['link_root'])

I get: PHP error: Undefined index: link_root

How do I iteratively set a value for a key/property of an array and why is this not working?

user3494047
  • 1,643
  • 4
  • 31
  • 61
  • 2
    Try a `print_r()` or a `var_dump()` first to see whats in array `$my_array`.. Secondly, the array you're trying to write to while looping is a copy. – Xorifelse Nov 16 '16 at 21:54

1 Answers1

3

The foreach control structure does not pass the value by reference by default.

If you want to be able modify the array internally, you need to use & to indicate you want it passed as a reference like so:

foreach ($myArray as &$array) {
    $array['link_root'] = "a string";
}

print($myArray[0]['link_root']);

The difference is subtle. Another way to do this is pass the index and reference it directly like:

foreach ($myArray as $index => $array) {
    $myArray[$index]['link_root'] = "a string";
}

print($myArray[0]['link_root']);

Reference: http://php.net/manual/en/control-structures.foreach.php

Jeremy Harris
  • 24,318
  • 13
  • 79
  • 133