php foreach over an array and assignment of this array

I want to add a value to an array while foreaching it :

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 ok but the object added disapear when I leave the loop ant print the array.

I guess this is a normal behaviour, what is the best way to work around this "feature" ?

Answers


Just call $cell by reference like this:

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

And it should retain the value. Passing by reference.


When you iterate over the array, $cell is a copy of the value, not a reference so changing it will not effect the value in the array.

You should either use & to make the $cell a reference:

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

Or access the array items directly using an index.

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

Need Your Help

Errors at Embedded Cassandra server startup

unit-testing cassandra

I am trying to use EmbeddedCassandraService to instantiate a Cassandra server in my unit tests. But I am getting this error. Any idea what can be causing this?

Query a listValue in an Entity using Google Datastore API

google-app-engine google-datastore google-cloud-datastore

Is it possible to query a listValue from an Entity using the Google Cloud Datastore API.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.