note 101920 deleted from function.array-key-exists by crell

From: Date: Wed, 29 Jun 2022 20:45:37 +0000
Subject: note 101920 deleted from function.array-key-exists by crell
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-218769@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; } ?>

« previous php.notes (#218769) next »