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

[韓日関係] 首相含む大幅な内閣改造の可能性…早ければ来月10日ごろ=韓国

div not scrolling properly with slimScroll plugin

I am using the slimScroll plugin for jQuery by Piotr Rochala Which is a great plugin for nice scrollbars on most browsers but I am stuck because I am using it for a chat box and whenever the user appends new text to the boxit does scroll using the .scrollTop() method however the plugin's scrollbar doesnt scroll with it and when the user wants to look though the chat history it will start scrolling from near the top. I have made a quick demo of my situation http://jsfiddle.net/DY9CT/2/ Does anyone know how to solve this problem?

Why does this javascript based printing cause Safari to refresh the page?

The page I am working on has a javascript function executed to print parts of the page. For some reason, printing in Safari, causes the window to somehow update. I say somehow, because it does not really refresh as in reload the page, but rather it starts the "rendering" of the page from start, i.e. scroll to top, flash animations start from 0, and so forth. The effect is reproduced by this fiddle: http://jsfiddle.net/fYmnB/ Clicking the print button and finishing or cancelling a print in Safari causes the screen to "go white" for a sec, which in my real website manifests itself as something "like" a reload. While running print button with, let's say, Firefox, just opens and closes the print dialogue without affecting the fiddle page in any way. Is there something with my way of calling the browsers print method that causes this, or how can it be explained - and preferably, avoided? P.S.: On my real site the same occurs with Chrome. In the ex