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);
2
  • 2
    your array is not cleared, is it multidimensional or associative array please update your actual array Commented Apr 21, 2017 at 11:22
  • More generalized advice on changing keys: Fastest way to add prefix to array keys? Commented May 14, 2023 at 7:41

6 Answers 6

5

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://3v4l.org/p9WFK

Sign up to request clarification or add additional context in comments.

Comments

2

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);

Comments

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.

1 Comment

str_replace() can be called on arrays. stackoverflow.com/a/17764214/2943403
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]];
}

1 Comment

Replace $outputArray[ $key ] = $firstAray[ $i ] with $outputArray[ $key ] = $firstArray[$keys[$i]]
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;
}

Comments

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)

1 Comment

Posted many years earlier stackoverflow.com/a/17764214/2943403

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.