note 101918 deleted from function.array-key-exists by thiago
| From: | thiago@php.net | Date: | Tue, 18 Jan 2011 11:05:29 +0000 |
| Subject: | note 101918 deleted from function.array-key-exists by thiago | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-175855@lists.php.net to get a copy of this message | ||
Note Submitter: tech at signhere envy dot de
----
Hey, this function is able to rename a key inside an array.
If the key to be replaced doesn't exist inside the array, or the new key already exists in the
array, the function will return FALSE.
Otherwise, the array with the renamed key will be returned.
Hope this will be useful for someone.
<?php
function array_rename_key($array, $key, $newkey){
if( ! array_key_exists($key, $array) || array_key_exists($newkey, $array)) return FALSE;
$uid = uniqid(''); //To clearly identify the Element.
$preserve_value = $array[$key]; //Keep the Value
$array[$key] = $uid; //Overwrite Value with ID
$array = array_flip($array); //Flip the Array keys and values
$array[$uid] = $newkey; //Set Value of the ID with new Key.
$array = array_flip($array); //Everything back in Place.
$array[$newkey] = $preserve_value;
return $array;
}
?>