php shuffle array keys

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

Define array to for shuffle keys

$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'
);

Define array indexes to get random keys in while loop

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

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

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;
	}
}

Print Array to see shuffled array key result

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
)

This complete code of function

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;
}

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>