php shuffle array keys

0.73K views
no comments
7 Sep 2014 10:55 am

Define array to for shuffle keys

[php]$numbers = array(
‘one’ => ‘one_1′
,’two’ => ‘two_2′
,’three’ => ‘three_3′
,’four’ => ‘four_4′
,’five’ => ‘five_5′
,’six’ => ‘six_6′
,’seven’ => ‘seven_7′
,’eight’ => ‘eight_8′
,’nine’ => ‘nine_9′
,’ten’ => ‘ten_10’
);
[/php]

Define array indexes to get random keys in while loop

[php]foreach($numbers as $num_key=>$num_val){
$array_keys[$num_key] =$num_key;
}

[/php]

Assign array keys in random order, they will be shuffled in while loop and

[php]while(true){
$array_randkey = array_rand($array_keys);
$val = $numbers[$array_randkey];
if($val!==null){
$shuffeled_keys[$array_randkey] = $numbers[$array_randkey];
unset($numbers[$array_randkey]);
}
if(empty($numbers)){
break;
}
}
[/php]

Print Array to see shuffled array key result

[php]print_r($shuffeled_keys);
//Shuffled Keys result
Array
(
[one] => one_1
[four] => four_4
[three] => three_3
[ten] => ten_10
[two] => two_2
[six] => six_6
[seven] => seven_7
[nine] => nine_9
[five] => five_5
[eight] => eight_8
)
[/php]

This complete code of function

[php]
function shuffle_arraykeys(array $arraydata()){
foreach($arraydata as $num_key=>$num_val){
$array_keys[$num_key] =$num_key;
}
while(true){
$array_randkey = array_rand($array_keys);
$val = $numbers[$array_randkey];
if($val!==null){
$shuffeled_keys[$array_randkey] = $numbers[$array_randkey];
unset($numbers[$array_randkey]);
}
if(empty($numbers)){
break;
}
}
return $shuffeled_keys;
}
[/php]

NOTE:Your Email Address will be not shown and please do not add spamming comments because here is REL="NOFOLLOW" on your links and comments also moderated shown.
<code>Put html css or any language code under this tag</code>