In PHP, how do you change the key of an array element?

$arr[$newkey] = $arr[$oldkey];
unset($arr[$oldkey]);

The way you would do this and preserve the ordering of the array is by putting the array keys into a separate array, find and replace the key in that array and then combine it back with the values.

Here is a function that does just that:

function change_key( $array, $old_key, $new_key ) {

    if( ! array_key_exists( $old_key, $array ) )
        return $array;

    $keys = array_keys( $array );
    $keys[ array_search( $old_key, $keys ) ] = $new_key;

    return array_combine( $keys, $array );
}

if your array is built from a database query, you can change the key directly from the mysql statement:

instead of

"select ´id´ from ´tablename´..."

use something like:

"select ´id´ **as NEWNAME** from ´tablename´..."