Categories
PHP

Shuffle Array and Get Random Elements

If you want to randomize the order of elements in the array use the shuffle() function. Or use array_rand() function to grab one or more random elements out of an array.

  1. Shuffle Array
  2. Shuffle Associative Array
  3. Get random elements out of an array

Shuffle Array

The shuffle function randomly sorts the order of the values in an array. It does not maintain the keys/values association.

<?php
 $a = [1,2,3,4,5];
 shuffle($a);
 print_r($a);
 
 /*outputs
Array
(
    [0] => 4
    [1] => 5
    [2] => 1
    [3] => 2
    [4] => 3
) */

You can use shuffle with an associative array, but the keys will lose:

<?php
 $a = ['one'=>1,'two'=>2,'three'=>3,'four'=>4,'five'=>5];
 shuffle($a);
 print_r($a);
 
 /*outputs
 Array
(
    [0] => 5
    [1] => 4
    [2] => 2
    [3] => 1
    [4] => 3
) */

Shuffle Associative Array

To shuffle associative arrays, we created a shuffleAssociative function:

<?php
 function shuffleAssociative ($a){
  $keys = array_keys($a);
  shuffle ($keys);
  $newArray = [];
  foreach ($keys as $v){	
   $newArray[$v] = $a[$v];
  }
  return $newArray;
 }

The array_keys function returns an array of all the keys in the associative array. We shuffled the keys and returned a new Array created with shuffled keys. See the complete example:

<?php
 function shuffleAssociative ($a){
  $keys = array_keys($a);
  shuffle ($keys);
  $newArray = [];
  foreach ($keys as $v){	
   $newArray[$v] = $a[$v];
  }
  return $newArray;
 }
 $a = ['one'=>1,'two'=>2,'three'=>3,'four'=>4,'five'=>5];
 $b = shuffleAssociative($a);
 print_r($b);
 
/*outputs
Array
(
    [three] => 3
    [two] => 2
    [four] => 4
    [one] => 1
    [five] => 5
) */

array_rand get random elements out of arrays

With array_rand(), one or more random elements out of an array are determined by random.

<?php
 //Syntax
 array_rand(array $array, int $num = 1): int|string|array

The first parameter for this function is the array; the second (optional) one is the number of elements to be returned. This function returns an array of keys if you want 2 or more random elements.

Example: array_rand()

<?php
 $a = ['one'=>1,'two'=>2,'three'=>3,'four'=>4,'five'=>5];
 $b = [1,2,3,4,5]; 

 $r = array_rand($a); 
 echo $a[$r]; //2
 
 $r = array_rand($b); 
 echo $b[$r]; //4
 
 $r = array_rand($b, 2);
 foreach ($r as $v)
   echo $b[$v]. ' '; // 3 5

If you do not want to pick random elements but want to randomize the order of elements in the array (for example, when shuffling a deck of cards), use the shuffle() function.


More Posts on PHP Sorting Arrays:

  1. Sort arrays in ascending or descending order
  2. Sort associative arrays
  3. Sort with user-defined criteria/function
  4. Sort multiple or multidimensional arrays
  5. Sort nested arrays
  6. Natural alphanumeric sort order
  7. Shuffle arrays grab random elements
  8. Working with arrays