user3494047 user3494047 - 11 months ago 47
PHP Question

attempting to assign a property to an array

I have an array called

I created $my_array like this:

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

Each element of
is an array:

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

array /// array /// array /// array ///

foreach ($my_array as $array){

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

print(" ///// ");

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

and then when I try:


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 Source

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";


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";