Change multiple values in Array

Hi,

Is there a way i can take this array:


$test = array('key1'=>'test1', 'key2'=>'value2', 
'key3'=>array('test','test1','test2'));

And replace all instances of ‘test’ with ‘frog’?

I tried doing this:


$test = array('key1'=>'test1', 'key2'=>'value2', 
'key3'=>array('test','test1','test2'));

$result = str_replace('test', 'frog', $test);

print_r($test);

But had no luck…

Can anyone point me in the right direction?

Thanks


<?php
$array = array(
  'one'   => 'foo',
  'two'   => 'bar',
  'three' => 'foobar',
  'four'  => array(
    'foo',
    'bar',
    'foo'
  )
);

function transform(&$value){
  $value = str_replace('foo', 'bar', $value);
}

array_walk_recursive(
  $array,
  'transform'
);

print_r(
  $array
);

/*
Array
(
  [one] => bar
  [two] => bar
  [three] => barbar
  [four] => Array
    (
    [0] => bar
    [1] => bar
    [2] => bar
    )
)
*/
?>

Thanks Anthony!

Works perfectly, i managed to get the other method working also:


<?php
$test = array('key1'=>'test1', 'key2'=>'value2', 'key3'=>array('test','test1','test2'));

function my_str_replace($srch, $replace, $subject){
    if(!is_array($subject)) return str_replace ($srch, $replace, $subject); 
    $out = array();
    foreach ($subject as $key => $value) $out[$key] = my_str_replace($srch, $replace, $value);
    return $out;    
}
$a  = my_str_replace('test', 'hello', $test);
print_r($a);
?>

But your code is a lot simpler and also easier to read :smiley:

Thanks

Hey,

I tried with your above method but it didn’t work so i tried doing this:


    $test = array('key1'=>'test1', 'key2'=>'value2', 'key3'=>array('test','test1','test2'));

    $new_test = array();

    foreach($test as $key=>$value) {
        if (strpos($value, 'test') !== FALSE) {i 
        $new_test[$key] = str_replace($value, 'hello', 'test');
        } else {
        $new_test[$key] = $value;
        }
    }

    print_r($new_test);

It nearly worked but i got this error:

Warning: strpos() expects parameter 1 to be string, array given in /public_html/view/phptest.php on line 7

Any ideas what i’m doing wrong?


<?php
		$test = array('key1'=>'test1', 'key2'=>'value2', 'key3'=>array('test','test1','test2'));
		
		array_walk_recursive(
			$test,
			function(&$value) {
				$value = str_replace('test', 'frog', $value);
			}
		);

		print_r($test); 
?>

EDIT: Actually… doesn’t work.
EDIT: Wanted array_walk_recursive instead.

Woops silly me :wink:

Ok that gives me the following:

Array ( [key1] => frog1 [key2] => value2 [key3] =>
Array ( [0] => test [1] => test1 [2] => test2 ) )

So it has changed the first one but now all of them…

Am i missing something? It needs to change “test1” and “test2” also…

You should print_r($result), not print_r($test) seeing you haven’t changed it.