ConFoo Montreal 2026: Call for Papers

Voting

: seven plus zero?
(Example: nine)

The Note You're Voting On

xzero at elite7hackers dot net
10 years ago
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 <[email protected]>
* @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
)

<< Back to user notes page

To Top