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

Why is this Javascript much *slower* than its jQuery equivalent?

I have a HTML list of about 500 items and a "filter" box above it. I started by using jQuery to filter the list when I typed a letter (timing code added later): $('#filter').keyup( function() { var jqStart = (new Date).getTime(); var search = $(this).val().toLowerCase(); var $list = $('ul.ablist > li'); $list.each( function() { if ( $(this).text().toLowerCase().indexOf(search) === -1 ) $(this).hide(); else $(this).show(); } ); console.log('Time: ' + ((new Date).getTime() - jqStart)); } ); However, there was a couple of seconds delay after typing each letter (particularly the first letter). So I thought it may be slightly quicker if I used plain Javascript (I read recently that jQuery's each function is particularly slow). Here's my JS equivalent: document.getElementById('filter').addEventListener( 'keyup', function () { var jsStart = (new Date).getTime()...

Is it possible to have IF statement in an Echo statement in PHP

Thanks in advance. I did look at the other questions/answers that were similar and didn't find exactly what I was looking for. I'm trying to do this, am I on the right path? echo " <div id='tabs-".$match."'> <textarea id='".$match."' name='".$match."'>". if ($COLUMN_NAME === $match) { echo $FIELD_WITH_COLUMN_NAME; } else { } ."</textarea> <script type='text/javascript'> CKEDITOR.replace( '".$match."' ); </script> </div>"; I am getting the following error message in the browser: Parse error: syntax error, unexpected T_IF Please let me know if this is the right way to go about nesting an IF statement inside an echo. Thank you.