note 101918 added to function.array-key-exists

From: Date: Tue, 18 Jan 2011 10:22:58 +0000
Subject: note 101918 added to function.array-key-exists
Groups: php.notes 
Request: Send a blank email to php-notes+get-175850@lists.php.net to get a copy of this message
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; } ?> ---- Server IP: 85.214.154.209 Probable Submitter: 212.6.175.122 ---- Manual Page -- http://www.php.net/manual/en/function.array-key-exists.php Edit -- https://master.php.net/note/edit/101918 Del: integrated -- https://master.php.net/note/delete/101918/integrated Del: useless -- https://master.php.net/note/delete/101918/useless Del: bad code -- https://master.php.net/note/delete/101918/bad+code Del: spam -- https://master.php.net/note/delete/101918/spam Del: non-english -- https://master.php.net/note/delete/101918/non-english Del: in docs -- https://master.php.net/note/delete/101918/in+docs Del: other reasons-- https://master.php.net/note/delete/101918 Reject -- https://master.php.net/note/reject/101918 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#175850) next »