Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have a pretty basic question but I am stuck. I am pretty new to php and I have an array like this:

$array = array(
    'one' => 1,
    'two' => array('key1' => 'val1','key2' => 'val2'),
    'three' => array('key1' => 'val1','key2' => 'val2'),
    'four' => array('key1' => 'val1','key2' => 'val2')
);

and for each of the arrays in the array (that is, 'two, 'three', and 'four'), I want to insert 'key3' => 'val3' into those arrays.

I tried this:

foreach($array as $item) {
    if (gettype($item) == "array") {
        $item['key3'] = 'val3';
    }
}

But it doesn't work, and I'm not sure why. Using various print_r's all over the place, it seems to insert 'key3' => 'val3' into $item if I print it out in the loop, but the original array seems unchanged. I also tried a regular for loop but that didn't work either.

share|improve this question
    
Do the key and its value are equals for each sub-array? –  sємsєм May 10 '13 at 22:58

2 Answers 2

up vote 10 down vote accepted

foreach works with a copy of $item, so you cannot modify your original array inside the foreach. One way to work around this is to use the & operator.

foreach($array as &$item) {
    if (is_array($item)) {
        $item['key3'] = 'val3';
    }
}

Another, more elegant way would be to use array_walk():

array_walk($array, function (&$v, $k) { 
    if (is_array($v)) {
        $v['key3'] = 'val3';
    }
});

This example will work from PHP 5.3, where Closures were introduced.

share|improve this answer
    
$item is only generated for the loop . You mean &$array['key3'] = 'val3'; ! –  moskito-x May 10 '13 at 23:55
    
@moskito-x I certainly mean what I wrote. That's the point of it. Check the foreach manual page I linked. –  kapa May 10 '13 at 23:59
    
To change $item is useless. Will be always overwritten by the next loop. –  moskito-x May 11 '13 at 0:01
    
@moskito-x codepad.org/GxZbQ1bD –  kapa May 11 '13 at 0:03
2  
But As foreach relies on the internal array pointer changing it within the loop may lead to unexpected behavior. therefore you have to unset the reference . unset($item); // break the reference with the last element. structures.foreach –  moskito-x May 11 '13 at 0:21

PHP has a function to check whether a variable is an array or not: is_array(). Use this:

if (is_array($item)) { ...
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.