K-2052
K-2052

Reputation: 197

Setting value in Nested Php Array

Hi I'm trying to loop through a array and set a keys value. Very basic question.

The Code I tried is below.

http://pastebin.com/d3ddab156

<?php
$testArray = array("bob1" => array( 'name' => "bob1", 'setTest' => '2'));

foreach($testArray as $item)
{
    $item['setTest'] = 'bob';
} 

print_r($testArray);

I imagine I'm missing something stupid here and it is going to be a D'oh! moment for me. What is wrong with it?

Thanks.

Upvotes: 0

Views: 139

Answers (2)

eCaroth
eCaroth

Reputation: 531

Or, if you have a lot of data in the array and want to avoid creating a complete copy of each element over every iteration, simply iterate over each element as a reference. Then only a reference to that item is created i memory and you can directly manipulate the array element by using $item:

$testArray = array("bob1" => array( 'name' => "bob1", 'setTest' => '2'));    

foreach($testArray as &$item)
{
    $item['setTest'] = 'bob';
} 

print_r($testArray);

NOTE: be sure to unset $item after the loop so you don't inadvertantly modify the array later by using that variable name.

Upvotes: 1

Jimmy Shelter
Jimmy Shelter

Reputation: 1540

You do:

$testArray = array("bob1" => array( 'name' => "bob1", 'setTest' => '2'));    

foreach($testArray as $item)
{
    $item['setTest'] = 'bob';
} 

print_r($testArray);

$item is a copy. You change the copy, not the real array. Try this:

$testArray = array("bob1" => array( 'name' => "bob1", 'setTest' => '2'));    

foreach($testArray as $key => $item)
{
    $testArray[$key]['setTest'] = 'bob';
} 

print_r($testArray);

Upvotes: 3

Related Questions