note 80004 modified in function.shuffle by danbrown
| From: | danbrown@php.net | Date: | Fri, 25 Jul 2008 17:49:48 +0000 |
| Subject: | note 80004 modified in function.shuffle by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-142725@lists.php.net to get a copy of this message | ||
Very fast way to shuffle associative array and keep key=>value
<?php
$tmp=array("one"=>1,"two"=>2,"three"=>3,"four"=>4);
$new=array();
$c=count($tmp);
$k=array_keys($tmp);
$v=array_values($tmp);
while($c>0) {
$i=array_rand($k);
$new[$k[$i]]=$v[$i];
unset($k[$i]); #exlude selected number from list
$c--;
}
print_r($tmp);
print_r($new);
?>
Result:
Array
(
[one] => 1
[two] => 2
[three] => 3
[four] => 4
)
Array
(
[two] => 2
[three] => 3
[four] => 4
[one] => 1
)
And thats all, folks!
--was--
Very fast way to shuffle associative array and keep key=>value
<?
$tmp=array("one"=>1,"two"=>2,"three"=>3,"four"=>4);
$new=array();
$c=count($tmp);
$k=array_keys($tmp);
$v=array_values($tmp);
while($c>0) {
$i=array_rand($k);
$new[$k[$i]]=$v[$i];
unset($k[$i]); #exlude selected number from list
$c--;
}
print_r($tmp);
print_r($new);
?>
Result:
Array
(
[one] => 1
[two] => 2
[three] => 3
[four] => 4
)
Array
(
[two] => 2
[three] => 3
[four] => 4
[one] => 1
)
And thats all, folks!
http://php.net/manual/en/function.shuffle.php