note 90946 added to function.shuffle
| From: | sivaji2009 at gmail dot com | Date: | Sun, 17 May 2009 21:07:54 +0000 |
| Subject: | note 90946 added to function.shuffle | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-155385@lists.php.net to get a copy of this message | ||
Here i wrote a custom shuffle function which preserves the array index and distributes the array
element randomly.
<?php
/*
* return an array whose elements are shuffled in random order.
*/
function custom_shuffle($my_array = array()) {
$copy = array();
while (count($my_array)) {
// takes a rand array elements by its key
$element = array_rand($my_array);
// assign the array and its value to an another array
$copy[$element] = $my_array[$element];
//delete the element from source array
unset($my_array[$element]);
}
return $copy;
}
$array = array(
'a' => 'apple',
'b' => 'ball',
'c' => 'cat',
'd' => 'dog',
'e' => 'egg',
'f' => 'fan',
'g' => 'gun'
);
print_r(custom_shuffle($array));
Array
(
[c] => cat
[e] => egg
[f] => fan
[a] => apple
[b] => ball
[g] => gun
[d] => dog
)
?>
----
Server IP: 59.162.86.8
Probable Submitter: 122.164.15.16
----
Manual Page -- http://www.php.net/manual/en/function.shuffle.php
Edit -- https://master.php.net/note/edit/90946
Del: integrated -- https://master.php.net/note/delete/90946/integrated
Del: useless -- https://master.php.net/note/delete/90946/useless
Del: bad code -- https://master.php.net/note/delete/90946/bad+code
Del: spam -- https://master.php.net/note/delete/90946/spam
Del: non-english -- https://master.php.net/note/delete/90946/non-english
Del: in docs -- https://master.php.net/note/delete/90946/in+docs
Del: other reasons-- https://master.php.net/note/delete/90946
Reject -- https://master.php.net/note/reject/90946
Search -- https://master.php.net/manage/user-notes.php