user3494047 user3494047 - 24 days ago 6
PHP Question

attempting to assign a property to an array

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?

Answer

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