Php foreach by array and assignment of this array

I want to add a value to the array as it passes:

foreach ($array as $cell) {
    if ($cell["type"] == "type_list") {
        $cell["list"] = $anObject;
        error_log(print_r($cell, TRUE), 0);
}
error_log(print_r($array, TRUE), 0);

The first printr is fine, but the added object disappears when I leave the ant loop to print the array.

I think this is normal behavior, what is the best way to get around this “feature”?

+5
source share
2 answers

Just call $cellthe link:

foreach($array as &$cell) {...}

And he must keep the meaning. Follow the link .

+11
source

When you iterate over an array, it $cellis a copy of the value, not a reference, so changing it will not affect the value in the array.

&, $cell :

foreach ($array as &$cell) {
    if ($cell["type"] == "type_list") {
        $cell["list"] = $anObject;
        error_log(print_r($cell, TRUE), 0);
}
error_log(print_r($array, TRUE), 0);

.

foreach ($array as $i => $cell) {
    if ($array[$i]["type"] == "type_list") {
        $array[$i]["list"] = $anObject;
        error_log(print_r($array[$i], TRUE), 0);
}
error_log(print_r($array, TRUE), 0);
+4

All Articles