Last active
December 9, 2020 16:54
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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