Skip to content
Advertisement

replace all keys in php array

This is my array:

['apple']['some code'] 
['beta']['other code']
['cat']['other code 2 ']

how can I replace all the “e” letters with “!” in the key name and keep the values so that I will get something like that

['appl!']['some code'] 
['b!ta']['other code']
['cat']['other code 2 ']

I found this but because I don’t have the same name for all keys I can’t use It

$tags = array_map(function($tag) {
    return array(
        'name' => $tag['name'],
        'value' => $tag['url']
    );
}, $tags);

Advertisement

Answer

I hope your array looks like this:-

Array
(
    [apple] => some code
    [beta] => other code
    [cat] => other code 2 
)

If yes then you can do it like below:-

$next_array = array();
foreach ($array as $key=>$val){
     $next_array[str_replace('e','!',$key)] = $val;
}
echo "<pre/>";print_r($next_array);

output:- https://eval.in/780144

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement