Monday, May 7, 2012

Change array key without changing order


You can "change" the key of an array element simply by setting the new key and removing the old:




$array[$newKey] = $array[$oldKey];
unset($array[$oldKey]);



But this will move the key to the end of the array.



Is there some elegant way to change the key without changing the order?



(PS: This question is just out of conceptual interest, not because I need it anywhere.)


Source: Tips4all

5 comments:

  1. Tested and works :)

    $array = array( "a" => "1", "b" => "2", "c" => "3" );

    function replace_key($array, $old_key, $new_key) {
    $keys = array_keys($array);
    if (false === $index = array_search($old_key, $keys)) {
    throw new Exception(sprintf('Key "%s" does not exit', $old_key));
    }
    $keys[$index] = $new_key;
    return array_combine($keys, array_values($array));
    }

    $new_array = replace_key($array, "b", "e");

    ReplyDelete
  2. One way would be to simply use a foreach iterating over the array and copying it to a new array, changing the key conditionally while iterating, e.g. if $key === 'foo' then dont use foo but bar:

    function array_key_rename($array, $oldKey, $newKey)
    {
    foreach ($array as $key => $value) {
    $newArray[$key === $oldKey ? $newKey : $key] = $value;
    }
    return $newArray;
    }


    Another way would be to serialize the array, str_replace the serialized key and then unserialize back into an array again. That isnt particular elegant though and likely error prone, especially when you dont only have scalars or multidimensional arrays.

    A third way - my favorite - would be you writing array_key_rename in C and proposing it for the PHP core ;)

    ReplyDelete
  3. Something like this may also work:

    $langs = array("EN" => "English",
    "ZH" => "Chinese",
    "DA" => "Danish",
    "NL" => "Dutch",
    "FI" => "Finnish",
    "FR" => "French",
    "DE" => "German");
    $json = str_replace('"EN":', '"en":', json_encode($langs));
    print_r(json_decode($json, true));


    OUTPUT:

    Array
    (
    [en] => English
    [ZH] => Chinese
    [DA] => Danish
    [NL] => Dutch
    [FI] => Finnish
    [FR] => French
    [DE] => German
    )

    ReplyDelete
  4. Do a double flip! At least that is all I can think of:

    $array=("foo"=>"bar","asdf"=>"fdsa");
    $array=array_flip($array);
    $array["bar"]=>'newkey';
    $array=array_flip($array);

    ReplyDelete
  5. You could use array_combine. It merges an array for keys and another for values...

    For instance:

    $original_array =('foo'=>'bar','asdf'=>'fdsa');
    $new_keys = array('abc', 'def');
    $new_array = array_combine($new_keys, $original_array);

    ReplyDelete