Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to change values in JSON array via str_replace

Tags:

json

php

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);     
}
like image 318
Mother of Jesus Avatar asked Feb 01 '26 05:02

Mother of Jesus


1 Answers

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);     
} 
like image 128
SamHecquet Avatar answered Feb 02 '26 19:02

SamHecquet