Sunday, November 23, 2025
HomeLanguagesPHP shuffle() Function

PHP shuffle() Function

The shuffle() Function is a builtin function in PHP and is used to shuffle or randomize the order of the elements in an array. This function assigns new keys for the elements in the array. It will also remove any existing keys, rather than just reordering the keys and assigns numeric keys starting from zero.

Syntax: 

boolean shuffle($array)

Parameter: This function accepts a single parameter $array. It specifies the array we want to shuffle.

Return Value: This function returns a boolean value i.e., either True or False. It returns TRUE on success and FALSE on failure.

Note: This function will work for PHP version 4+.

Examples:  

Input:- array("a"=>"Ram", 
              "b"=>"Shita", 
              "c"=>"Geeta", 
              "d"=>"neveropen" )
Output:- array( [0] => Geeta,
                [1] => Shita,
                [2] => Ram,
                [3] => neveropen )
Explanation: Here as we can see that input contain elements 
             in a order but in output order become shuffled.

Below programs illustrates the working of shuffle() in PHP:  

  • When the input array is an associative array, then the shuffle() function will randomize the order of elements as well as assigns new keys to the elements starting from zero (0).

PHP




<?php
  
// input array contain some elements which
// need to be shuffled.
$a = array
     (  
        "a"=>"Ram", 
        "b"=>"Shita", 
        "c"=>"Geeta", 
        "d"=>"neveropen"
     );
  
shuffle($a);
print_r($a);
  
?>


Output: 

Array
(
    [0] => neveropen
    [1] => Shita
    [2] => Ram
    [3] => Geeta
)
  • When the input array is not associative then the shuffle() function will randomize the order and convert the array to an associative array with keys starting from zero (0).

PHP




<?php
  
// input array contain some elements
// which need to be shuffled.
$a = array
     (
        "ram",
        "geeta",
        "blue",
        "red",
        "shyam"
     );
  
shuffle($a);
print_r($a);
  
?>


Output: 

Array
(
    [0] => red
    [1] => geeta
    [2] => ram
    [3] => shyam
    [4] => blue
)

Reference: 
http://php.net/manual/en/function.shuffle.php
 

RELATED ARTICLES

Most Popular

Dominic
32407 POSTS0 COMMENTS
Milvus
97 POSTS0 COMMENTS
Nango Kala
6785 POSTS0 COMMENTS
Nicole Veronica
11932 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12000 POSTS0 COMMENTS
Shaida Kate Naidoo
6907 POSTS0 COMMENTS
Ted Musemwa
7168 POSTS0 COMMENTS
Thapelo Manthata
6864 POSTS0 COMMENTS
Umr Jansen
6852 POSTS0 COMMENTS