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

 

Link to comment
Share on other sites

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

Link to comment
Share on other sites

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

 

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.