note 117379 added to function.shuffle
| From: | xzero at elite7hackers dot net | Date: | Sat, 30 May 2015 13:09:04 +0000 |
| Subject: | note 117379 added to function.shuffle | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-202708@lists.php.net to get a copy of this message | ||
There is an function which uses native shuffle() but preserves keys, and their order, so at end,
only values are shuffled.
<?PHP
/**
* Array Quake - Give an array good quake so every value will endup with random given space.
* Keys, and their order are preserved.
* @author xZero <xzero@elite7hackers.net>
* @param array $array
* @return boolean false on failure
*/
function array_quake(&$array) {
if (is_array($array)) {
$keys = array_keys($array); // We need this to preserve keys
$temp = $array;
$array = NULL;
shuffle($temp); // Array shuffle
foreach ($temp as $k => $item) {
$array[$keys[$k]] = $item;
}
return;
}
return false;
}
// Example
$numbers = array(
'ZERO' => 0,
'ONE' => 1,
'TWO' => 2,
'THREE' => 3,
'FOUR' => 4,
'FIVE' => 5,
'SIX' => 6,
'SEVEN' => 7,
'EIGHT' => 8,
'NINE' => 9
);
echo "\nBefore (original):\n";
print_r($numbers);
array_quake($numbers);
echo "\n\nAfter (Array Quake);\n";
print_r($numbers);
echo "\n";
?>
Result example:
Before (original):
Array
(
[ZERO] => 0
[ONE] => 1
[TWO] => 2
[THREE] => 3
[FOUR] => 4
[FIVE] => 5
[SIX] => 6
[SEVEN] => 7
[EIGHT] => 8
[NINE] => 9
)
After (Array Quake);
Array
(
[ZERO] => 4
[ONE] => 2
[TWO] => 0
[THREE] => 8
[FOUR] => 3
[FIVE] => 6
[SIX] => 1
[SEVEN] => 7
[EIGHT] => 5
[NINE] => 9
)
----
Server IP: 72.52.91.14
Probable Submitter: 2.248.32.254
----
Manual Page -- http://php.net/manual/en/function.shuffle.php
Edit -- https://master.php.net/note/edit/117379
Del: integrated -- https://master.php.net/note/delete/117379/integrated
Del: useless -- https://master.php.net/note/delete/117379/useless
Del: bad code -- https://master.php.net/note/delete/117379/bad+code
Del: spam -- https://master.php.net/note/delete/117379/spam
Del: non-english -- https://master.php.net/note/delete/117379/non-english
Del: in docs -- https://master.php.net/note/delete/117379/in+docs
Del: other reasons-- https://master.php.net/note/delete/117379
Reject -- https://master.php.net/note/reject/117379
Search -- https://master.php.net/manage/user-notes.php