How to add a column to an existing multidimensional php array and then change value in one of it’s columns

If you want to add column to an existing PHP array you can do in accessing it by reference.

In following example there is an array containing records of months numbers and names. We’d like to add a new column called ‘temperature’ containing our opinion about it. Then we’d like to change only one record of the array to express our preferences.The months array can be created like this:

$months = [
[‘nr’ => ‘1’, ‘name’ => ‘Jan’],
[‘nr’ =>’2′, ‘name’ => ‘Feb’],
[‘nr’ =>’3′, ‘name’ => ‘Mar’],
[‘nr’ =>’4′, ‘name’ => ‘Apr’],
[‘nr’ =>’5′, ‘name’ => ‘May’],
[‘nr’ =>’6′, ‘name’ => ‘Jun’],
[‘nr’ =>’7′, ‘name’ => ‘Jul’],
[‘nr’ =>’8′, ‘name’ => ‘Aug’],
[‘nr’ =>’9′, ‘name’ => ‘Sep’],
[‘nr’ =>’10’, ‘name’ => ‘Oct’],
[‘nr’ =>’11’, ‘name’ => ‘Nov’],
[‘nr’ =>’12’, ‘name’ => ‘Dec’],
];

Then let’s add one column using reference:

foreach ($months as &$record) {

$record[‘temperature’] = ‘hmmm…’;

}

And finally let’s change only one record:

foreach ($months as &$record) {

if ($record[‘name’] === ‘Sep’) {

$record[‘temperature’] = ‘my favorite’;

}

}

Leave a comment

Your email address will not be published. Required fields are marked *