3

I would like to change values in an array. Here is my starting array:

Array
(
    [0] => Array
        (
            [name] => aaa         
        )

    [1] => Array
        (
            [name] => bbb            
        )

    [2] => Array
        (
            [name] => ccc
        )
)

I declare a searchterm (eg. "aaa") and a new name for it (eg. "test"). And than I do a str_replace to actually change it. Unfortunately nothing changes nor do I get an error message. Can you please help and tell me where my error is please?

for ($i=0; $i < count($json) ; $i++) { 
    $search  = $old_name;
    $replace = $new_name;
    str_replace($search, $replace, $json[$i]['name']); 
    print_r($json);     
}

3 Answers 3

3

As the documentation says, this function doesn't update the array

This function returns a string or an array with the replaced values.

you need to update it with the returned value:

for ($i=0; $i < count($json) ; $i++) { 
    $search  = $old_name;
    $replace = $new_name;
    $json[$i]['name'] = str_replace($search, $replace, $json[$i]['name']);
    print_r($json);     
} 
Sign up to request clarification or add additional context in comments.

Comments

3

str_replace returns a string. I think you are trying to use it as though it alters a parameter that was passed by reference. Instead you should assign the returned value to the array at the correct index.

for ($i=0; $i < count($json) ; $i++) { 
    $search  = $old_name;
    $replace = $new_name;
   $json[$i]['name'] = str_replace($search, $replace, $json[$i]['name']); 
    print_r($json);     
}

Comments

2

If you want to replace/change more than one name, I suggest you to use the below code.

// define an array with keys as new name and value as old name ( name to be replaced).
$change_name_array= array('test'=>'aaa','another_test'=>'bbb');
// loop the array  
for ($i=0; $i < count($json) ; $i++) { 
    // check if the name is in defined array
    if(in_array($json[$i]['name'],$change_name_array)){
        // get the key and replace it. 
        $json[$i]['name'] = array_search($json[$i]['name'], $change_name_array);
    }
}

Out put: here aaa id replaced with test and bbb is replaced with another_test

Array
(
    [0] => Array
        (
            [name] => test
        )

    [1] => Array
        (
            [name] => another_test
        )

    [2] => Array
        (
            [name] => ccc
        )

)

Comments

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.