phparraysreplacekeyprefix

Replace leading substring before a delimiter in all array keys


I have an array like below.

$arr = Array ( [My_name] => Sam [My_location] => United_Kingdom [My_id] => 1 );

I'm trying to change the keys:

So the final array would look like

Array ( [Your_name] => Sam [Your_location] => United_Kingdom [Your_id] => 1 );

I was hoping something like str_replace() would work

 $arrnew = str_replace("My","Your",$arr);

But this is only replacing "My" to "Your" if "My" is a value, not a key.

So how would I change the keys?


Solution

  • str_replace() doesn't work on keys, so isolate the array keys as values then mutate them, re-combine the new keys with the original values.

    $arrnew = array_combine(
        str_replace(
            "My",
            "Your",
            array_keys($arr)
        ),
        $arr
    );