note 83007 modified in function.shuffle by danbrown

From: Date: Fri, 25 Jul 2008 17:50:10 +0000
Subject: note 83007 modified in function.shuffle by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-142726@lists.php.net to get a copy of this message
Another shuffle() implementation that preserves keys, does not use extra memory and perhaps is a bit easier to grasp. <?php if (function_exists('shuffle_with_keys')===false) { function shuffle_with_keys(&$array) { /* Auxiliary array to hold the new order */ $aux = array(); /* We work with an array of the keys */ $keys = array_keys($array); /* We shuffle the keys */ shuffle($keys); /* We iterate thru' the new order of the keys */ foreach($keys as $key) { /* We insert the key, value pair in its new order */ $aux[$key] = $array[$key]; /* We remove the element from the old array to save memory */ unset($array[$key]); } /* The auxiliary array with the new order overwrites the old variable */ $array = $aux; } } ?> --was-- Another shuffle() implementation that preserves keys, does not use extra memory and perhaps is a bit easier to grasp. if (function_exists('shuffle_with_keys')===false) { function shuffle_with_keys(&$array) { /* Auxiliary array to hold the new order */ $aux = array(); /* We work with an array of the keys */ $keys = array_keys($array); /* We shuffle the keys */ shuffle($keys); /* We iterate thru' the new order of the keys */ foreach($keys as $key) { /* We insert the key, value pair in its new order */ $aux[$key] = $array[$key]; /* We remove the element from the old array to save memory */ unset($array[$key]); } /* The auxiliary array with the new order overwrites the old variable */ $array = $aux; } } http://php.net/manual/en/function.shuffle.php

« previous php.notes (#142726) next »