2

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);
Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
user186585
  • 512
  • 1
  • 8
  • 25
  • 2
    your array is not cleared, is it multidimensional or associative array please update your actual array – lazyCoder Apr 21 '17 at 11:22
  • More generalized advice on changing keys: [Fastest way to add prefix to array keys?](https://stackoverflow.com/q/2607595/2943403) – mickmackusa May 14 '23 at 07:41

6 Answers6

4

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

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
2

You can stick with array_map actually. It is not really practical, but as a prove of concept, this can be done like this:

$array = array_combine(
    array_map(function ($key) {
        return str_replace('e', '!', $key);
    }, array_keys($array)),
    $array
);

We use array_keys function to extract keys and feed them to array_map. Then we use array_combine to put keys back to place.

Here is working demo.

sevavietl
  • 3,762
  • 1
  • 14
  • 21
1

Here we are using array_walk and through out the iteration we are replacing e to ! in key and putting the key and value in a new array.

Try this code snippet here

<?php
$firstArray = array('apple'=>'some code','beta'=>'other code','cat'=>'other code 2 ');
$result=array();
array_walk($firstArray, function($value,$key) use (&$result) {
    $result[str_replace("e", "!", $key)]=$value;
});
print_r($result);
Sahil Gulati
  • 15,028
  • 4
  • 24
  • 42
0

If you got this :

$firstArray = array('apple'=>'some code','beta'=>'other code','cat'=>'other code 2 ');

You can try this :

$keys        = array_keys($firstArray);
$outputArray = array();
$length      = count($firstArray);

for($i = 0; $i < $length; $i++)
{
    $key = str_replace("e", "!", $keys[ $i ]);
    $outputArray[ $key ] = $firstArray[$keys[$i]];
}
Thomas Rollet
  • 1,573
  • 4
  • 19
  • 33
0

We can iterate the array and mark all problematic keys to be changed. Check for the value whether it is string and if so, make sure the replacement is done if needed. If it is an array instead of a string, then call the function recursively for the inner array. When the values are resolved, do the key replacements and remove the bad keys. In your case pass "e" for $old and "!" for $new. (untested)

function replaceKeyValue(&$arr, $old, $new) {
    $itemsToRemove = array();
    $itemsToAdd = array();
    foreach($arr as $key => $value) {
        if (strpos($key, $old) !== false) {
            $itemsToRemove[]=$key;
            $itemsToAdd[]=str_replace($old,$new,$key);
        }
        if (is_string($value)) {
            if (strpos($value, $old) !== false) {
                $arr[$key] = str_replace($old, $new, $value);
            }
        } else if (is_array($value)) {
            $arr[$key] = replaceKeyValue($arr[$key], $old, $new);
        }
    }
    for ($index = 0; $index < count($itemsToRemove); $index++) {
        $arr[$itemsToAdd[$index]] = $itemsToRemove[$index];
        unset($arr[$itemsToRemove[$index]]);
    }
    return $arr;
}
Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
0

Another option using just 2 lines of code:

Given:

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

Do:

$replacedKeys = str_replace('e', '!', array_keys($array));
return array_combine($replacedKeys, $array);

Explanation:

str_replace can take an array and perform the replace on each entry. So..

  1. array_keys will pull out the keys (https://www.php.net/manual/en/function.array-keys.php)
  2. str_replace will perform the replacements (https://www.php.net/manual/en/function.str-replace.php)
  3. array_combine will rebuild the array using the keys from the newly updated keys with the values from the original array (https://www.php.net/manual/en/function.array-combine.php)
Adam
  • 31
  • 5