Skip to main content

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

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

Post a Comment

Popular posts from this blog

Slow Android emulator

I have a 2.67 GHz Celeron processor, 1.21 GB of RAM on a x86 Windows XP Professional machine. My understanding is that the Android emulator should start fairly quickly on such a machine, but for me it does not. I have followed all instructions in setting up the IDE, SDKs, JDKs and such and have had some success in staring the emulator quickly but is very particulary. How can I, if possible, fix this problem?

CCNA 1 Final Exam 2011 latest (hot hot hot)

  Hi! I have been posted content of ccna1 final exam (latest and only question.) I will post the answer and insert image on sunday. If you care, please subscribe your email an become a first person have full test content. Subcribe now  Some question  have not content because this question have images content. So that can you wait for me? SUNDAY 1. A user sees the command prompt: Router(config-if)# . What task can be performed at this mode? Reload the device. Perform basic tests. Configure individual interfaces. Configure individual terminal lines. 2. Refer to the exhibit. Host A attempts to establish a TCP/IP session with host C. During this attempt, a frame was captured with the source MAC address 0050.7320.D632 and the destination MAC address 0030.8517.44C4. The packet inside the captured frame has an IP source address 192.168.7.5, and the destination IP address is 192.168.219.24. At which point in the network was this packet captured? leaving host A leaving ATL leaving...