0

I want to change 'value2' to 'My string'. I know this is possible by using the array keys but I wonder if it's a cleaner way.

$nested_array[] = array('value1', 'value2', 'value3');

foreach($nested_array as $values){

    foreach($values as $value){

        if($value == 'value2'){
            $value = 'My string';
        }

    }

}

5 Answers 5

7

Just use the reference operator &to pass values by reference:

foreach($nested_array as &$values) {
    foreach($values as &$value) {
        do_something($value);
    }
}
unset($values); // These two lines are completely optional, especially when using the loop inside a
unset($value);  // small/closed function, but this avoids accidently modifying elements later on.
10
  • While this might work for the given example, you should keep in mind, that it is a bad idea to modify the array, over which you are iterating. Especially when you add/remove items. Commented Jul 23, 2013 at 9:10
  • 2
    You should not forget to unset($value) after the loop – otherwise accessing that variable afterwards in your code might have unexpected side effects. Commented Jul 23, 2013 at 9:11
  • As long as you only modify values you're pretty much save. Changing the array itself is something different, but that's something you have to consider no matter which kind of loop you're using. Commented Jul 23, 2013 at 9:12
  • 1
    If you want to be 100% safe, yes, added those two lines to the example. Commented Jul 23, 2013 at 9:15
  • 1
    Yes, I understood you, you'll need it in both cases, because otherwise you'll create a copy again (at least on that level), so you won't modiy the original value. Commented Jul 23, 2013 at 9:23
3

You could also use array_walk_recursive for this:

array_walk_recursive($nested_array,
                     function(&$v) {
                         if ($v == 'value2') $v = 'My string';
                     }
);

This would work for any level of nesting and you don't need to remember to unset anything afterwards.

0

The PHP function array_search is what you 're searching for.

$key = array_search('value2', $nested_array);
$nested_array[$key] = 'My String';

This solution would be more performant than iterating through the whole array.

2
  • doesn't help for nested arrays, as you would need to add some kind of recursion to support infinite depth. Your example will fail, because $nested_array contains an array of values - not the values. Commented Jul 23, 2013 at 9:12
  • 1
    Okay ... for nested arrays you could use the RecursiveArrayIterator object of the SPL deliverd with php. Look for the second user comment at php.net/manual/en/class.recursivearrayiterator.php. This should solve your problem on a very smart way. Commented Jul 23, 2013 at 9:13
0

By using array keys:

$nested_array = array();
$nested_array[] = array('value1', 'value2', 'value3');

foreach($nested_array as $key => $values){

    foreach($values as $key2 => $value){

        if($value == 'value2'){
            $nested_array[$key][$key2] = 'My string';
        }
    }
}
var_export($nested_array);
// array ( 0 => array ( 0 => 'value1', 1 => 'My string', 2 => 'value3', ), )
0
function strReplaceAssoc(array $replace, $subject) { 
   return str_replace(array_keys($replace), array_values($replace), $subject);    
}

$nested_array[] = array('value1', 'value2', 'value3');

foreach($nested_array as $values){

    foreach($values as $value){

        $replace = array( 
            'value2' => 'My string' 
            );

        $new_values = strReplaceAssoc($replace,$value);

       echo $new_values . '<br />';

    }

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.