Jump to content

Replace values in Array


billy_111

Recommended Posts

Hi,

 

If i had the following array:

 

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

 

Is there a way i could change all the values that have the word "test" to "hello"?

 

So basically end up with the following array:

 

$test = array('key1'=>'hello1', 'key2'=>'value2', 'key3'=>array('hello','hello1','hello2'));

 

Is this possible?

 

Thanks

Link to comment
https://forums.phpfreaks.com/topic/213199-replace-values-in-array/
Share on other sites

Thanks,

 

I just tried with this code:

 

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

    $new_test = array();

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

    print_r($new_test);

 

And i get this error:

 

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

 

Any ideas what this problem might be?

 

try

<?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);
?>

Thanks,

 

Your code worked!  :D

 

I also tried another method which also worked:

 

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

    function transform(&$value){
        $value = str_replace('test', 'frog', $value);
    }

    array_walk_recursive($test, 'transform');

    print_r($test);

 

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.