Shuffle an associative array, How to Shuffle/jumble an associative array while keeping key/value pairs.

PHP shuffle() Function

The shuffle() function shuffles or randomizes the order of the elements in the array.

Syntax:

shuffle(array)

Parameter:

an array(Required)

Return:

TRUE on success or FALSE on failure

Example 1:

<?php
  $array = array("white", "green", "red", "blue", "yellow", "purple");
  shuffle($array);
  print_r($array);
?>

Output:

Array
(
    [0] => blue
    [1] => red
    [2] => yellow
    [3] => white
    [4] => green
    [5] => purple
)

Example 2:

<?php
//Shuffle an associative array
$assoc_array = array("a" => "white",
  "b" => "green",
  "c" => "red",
  "d" => "blue",
  "e" => "yellow",
  "f" => "purple");

function shuffle_assoc_array(&$array) {
  if (!is_array($array))
    return $array;

  $keys = array_keys($array);
  shuffle($keys);
  $random = array();
  foreach ($keys as $key)
    $random[$key] = $array[$key];

  $array = $random;

  return TRUE;
}

shuffle_assoc_array($assoc_array);
print_r($assoc_array);
?>

Output 1:

Array
(
    [b] => green
    [f] => purple
    [c] => red
    [d] => blue
    [e] => yellow
    [a] => white
)

 

Tags