Skip to content

Instantly share code, notes, and snippets.

@MushuLeDragon
Last active December 9, 2020 16:54
Show Gist options
  • Save MushuLeDragon/02fdea942e442e6b9aac74fd6587d2cd to your computer and use it in GitHub Desktop.
Save MushuLeDragon/02fdea942e442e6b9aac74fd6587d2cd to your computer and use it in GitHub Desktop.
[PHP] Change array key without changing order : https://stackoverflow.com/a/8884153/7998119
<?php
namespace Src\App;
class ReplaceArrayKeyWhitoutChangingOrder
{
/**
* Function that replace an array key without changing the order of all keys
*
* @param array $array
* @param array $oldToNewKeyList
* @return array
*/
public static function replace_key(array $array, array $oldToNewKeyList): array
{
foreach ($oldToNewKeyList as $old_key => $new_key) {
$keys = array_keys($array);
if (false === $index = array_search($old_key, $keys, true)) {
throw new \Exception(sprintf('Key "%s" does not exist', $old_key));
}
$keys[$index] = $new_key;
$array = array_combine($keys, array_values($array));
}
return $array;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment