Replace keys in an array based on another lookup/mapping array

Viewed 541525

I have an associative array in the form key => value where key is a numerical value, however it is not a sequential numerical value. The key is actually an ID number and the value is a count. This is fine for most instances, however I want a function that gets the human-readable name of the array and uses that for the key, without changing the value.

I didn't see a function that does this, but I'm assuming I need to provide the old key and new key (both of which I have) and transform the array. Is there an efficient way of doing this?

25 Answers
$arr[$newkey] = $arr[$oldkey];
unset($arr[$oldkey]);

The answer from KernelM is nice, but in order to avoid the issue raised by Greg in the comment (conflicting keys), using a new array would be safer

$newarr[$newkey] = $oldarr[$oldkey];
$oldarr=$newarr;
unset($newarr);

You could use a second associative array that maps human readable names to the id's. That would also provide a Many to 1 relationship. Then do something like this:

echo 'Widgets: ' . $data[$humanreadbleMapping['Widgets']];

Simple benchmark comparison of both solution.

Solution 1 Copy and remove (order lost, but way faster) https://stackoverflow.com/a/240676/1617857

<?php
$array = ['test' => 'value', ['etc...']];

$array['test2'] = $array['test'];
unset($array['test']);

Solution 2 Rename the key https://stackoverflow.com/a/21299719/1617857

<?php
$array = ['test' => 'value', ['etc...']];

$keys = array_keys( $array );
$keys[array_search('test', $keys, true)] = 'test2';
array_combine( $keys, $array );

Benchmark:

<?php
$array = ['test' => 'value', ['etc...']];


for ($i =0; $i < 100000000; $i++){
    // Solution 1
}


for ($i =0; $i < 100000000; $i++){
    // Solution 2
}

Results:

php solution1.php  6.33s  user 0.02s system 99% cpu 6.356  total
php solution1.php  6.37s  user 0.01s system 99% cpu 6.390  total
php solution2.php  12.14s user 0.01s system 99% cpu 12.164 total
php solution2.php  12.57s user 0.03s system 99% cpu 12.612 total

This page has been peppered with a wide interpretation of what is required because there is no minimal, verifiable example in the question body. Some answers are merely trying to solve the "title" without bothering to understand the question requirements.

The key is actually an ID number and the value is a count. This is fine for most instances, however I want a function that gets the human-readable name of the array and uses that for the key, without changing the value.

PHP keys cannot be changed but they can be replaced -- this is why so many answers are advising the use of array_search() (a relatively poor performer) and unset().

Ultimately, you want to create a new array with names as keys relating to the original count. This is most efficiently done via a lookup array because searching for keys will always outperform searching for values.

Code: (Demo)

$idCounts = [
    3 => 15,
    7 => 12,
    8 => 10,
    9 => 4
];

$idNames = [
    1 => 'Steve',
    2 => 'Georgia',
    3 => 'Elon',
    4 => 'Fiona',
    5 => 'Tim',
    6 => 'Petra',
    7 => 'Quentin',
    8 => 'Raymond',
    9 => 'Barb'
];

$result = [];
foreach ($idCounts as $id => $count) {
    if (isset($idNames[$id])) {
        $result[$idNames[$id]] = $count;
    }
}
var_export($result);

Output:

array (
  'Elon' => 15,
  'Quentin' => 12,
  'Raymond' => 10,
  'Barb' => 4,
)

This technique maintains the original array order (in case the sorting matters), doesn't do any unnecessary iterating, and will be very swift because of isset().

You can use this function based on array_walk:

function mapToIDs($array, $id_field_name = 'id')
{
    $result = [];
    array_walk($array, 
        function(&$value, $key) use (&$result, $id_field_name)
        {
            $result[$value[$id_field_name]] = $value;
        }
    );
    return $result;
}

$arr = [0 => ['id' => 'one', 'fruit' => 'apple'], 1 => ['id' => 'two', 'fruit' => 'banana']];
print_r($arr);
print_r(mapToIDs($arr));

It gives:

Array(
    [0] => Array(
        [id] => one
        [fruit] => apple
    )
    [1] => Array(
        [id] => two
        [fruit] => banana
    )
)

Array(
    [one] => Array(
        [id] => one
        [fruit] => apple
    )
    [two] => Array(
        [id] => two
        [fruit] => banana
    )
)

This basic function handles swapping array keys and keeping the array in the original order...

public function keySwap(array $resource, array $keys)
{
    $newResource = [];

    foreach($resource as $k => $r){
        if(array_key_exists($k,$keys)){
            $newResource[$keys[$k]] = $r;
        }else{
            $newResource[$k] = $r;
        }
    }

    return $newResource;
}

You could then loop through and swap all 'a' keys with 'z' for example...

$inputs = [
  0 => ['a'=>'1','b'=>'2'],
  1 => ['a'=>'3','b'=>'4']
]

$keySwap = ['a'=>'z'];

foreach($inputs as $k=>$i){
    $inputs[$k] = $this->keySwap($i,$keySwap);
}

This function will rename an array key, keeping its position, by combining with index searching.

function renameArrKey($arr, $oldKey, $newKey){
    if(!isset($arr[$oldKey])) return $arr; // Failsafe
    $keys = array_keys($arr);
    $keys[array_search($oldKey, $keys)] = $newKey;
    $newArr = array_combine($keys, $arr);
    return $newArr;
}

Usage:

$arr = renameArrKey($arr, 'old_key', 'new_key');

best way is using reference, and not using unset (which make another step to clean memory)

$tab = ['two' => [] ];

solution:

$tab['newname'] = & $tab['two'];

you have one original and one reference with new name.

or if you don't want have two names in one value is good make another tab and foreach on reference

foreach($tab as $key=> & $value) {
    if($key=='two') { 
        $newtab["newname"] = & $tab[$key];
     } else {
        $newtab[$key] = & $tab[$key];
     }
}

Iterration is better on keys than clone all array, and cleaning old array if you have long data like 100 rows +++ etc..

One which preservers ordering that's simple to understand:

function rename_array_key(array $array, $old_key, $new_key) {
  if (!array_key_exists($old_key, $array)) {
      return $array;
  }
  $new_array = [];
  foreach ($array as $key => $value) {
    $new_key = $old_key === $key
      ? $new_key
      : $key;
    $new_array[$new_key] = $value;
  }
  return $new_array;
}

You can write simple function that applies the callback to the keys of the given array. Similar to array_map

<?php
function array_map_keys(callable $callback, array $array) {
    return array_merge([], ...array_map(
        function ($key, $value) use ($callback) { return [$callback($key) => $value]; },
        array_keys($array),
        $array
    ));
}

$array = ['a' => 1, 'b' => 'test', 'c' => ['x' => 1, 'y' => 2]];
$newArray = array_map_keys(function($key) { return 'new' . ucfirst($key); }, $array);

echo json_encode($array); // {"a":1,"b":"test","c":{"x":1,"y":2}}
echo json_encode($newArray); // {"newA":1,"newB":"test","newC":{"x":1,"y":2}}

Here is a gist https://gist.github.com/vardius/650367e15abfb58bcd72ca47eff096ca#file-array_map_keys-php.

Here is an experiment (test)

Initial array (keys like 0,1,2)

$some_array[] = '6110';//
$some_array[] = '6111';//
$some_array[] = '6210';//

I must change key names to for example human_readable15, human_readable16, human_readable17

Something similar as already posted. During each loop i set necessary key name and remove corresponding key from the initial array.

For example, i inserted into mysql $some_array got lastInsertId and i need to send key-value pair back to jquery.

$first_id_of_inserted = 7;//lastInsertId
$last_loop_for_some_array = count($some_array);


for ($current_loop = 0; $current_loop < $last_loop_for_some_array ; $current_loop++) {

$some_array['human_readable'.($first_id_of_inserted + $current_loop)] = $some_array[$current_loop];//add new key for intial array

unset( $some_array[$current_loop] );//remove already renamed key from array

}

And here is the new array with renamed keys

echo '<pre>', print_r($some_array, true), '</pre>$some_array in '. basename(__FILE__, '.php'). '.php <br/>';

If instead of human_readable15, human_readable16, human_readable17 need something other. Then could create something like this

$arr_with_key_names[] = 'human_readable';
$arr_with_key_names[] = 'something_another';
$arr_with_key_names[] = 'and_something_else';


for ($current_loop = 0; $current_loop < $last_loop_for_some_array ; $current_loop++) {

    $some_array[$arr_with_key_names[$current_loop]] = $some_array[$current_loop];//add new key for intial array

    unset( $some_array[$current_loop] );//remove already renamed key from array

    }
Related