PHP shuffle() Function

What is PHP shuffle() Function?

If you want to randomly change the order of an array elements, use shuffle() function. The change is permanent. So, when you don’t care about the keys, you can use this function safely.

Syntax:

shuffle(array)

Parameters:

The function has one parameter which is required-

array (Required): This is an array which the function operates on.

Return Values:

The function always returns TRUE.

Examples:

Example 1:

<pre>
<?php
$languages= ["PHP","MySQL","JavaScript","Python","Java"];
shuffle($languages);
echo "A random array key is-";
print_r($languages);
?>
</pre>

Output:

A random array key is-
Array
(
[0] => MySQL
[1] => Python
[2] => JavaScript
[3] => Java
[4] => PHP
)

Notes on shuffle() Function:

The shuffle() function removes the existing keys of the array and reorder numerically starting from zero no matter whether it is a indexed array (check the first example below) or associative array (check the second example below)-

<pre>
<?php
$languages= [5=>"PHP",10=>"MySQL",15=>"JavaScript",20=>"Python",25=>"Java"];
shuffle($languages);
echo"A random array key is-";
print_r($languages);
?>
</pre>

Output:

A random array key is-
Array
(
[0] => JavaScript
[1] => Java
[2] => MySQL
[3] => PHP
[4] => Python
)

<pre>
<?php
$languages= ["DB1"=>  "MySQL","DB2"=>"PostGRE","DB3"=>"Mongo","DB4"=>"Oracle"];
shuffle($languages);
echo"A random array key is-"."<br />";
print_r($languages);
?>
</pre>

Output:

A random array key is-
Array
(
[0] => MySQL
[1] => Oracle
[2] =>PostGRE
[3] => Mongo
)

Caution:

You’ll lose the keys of the original array after running this function.

Difference between shuffle() and array_rand() function:

  • shuffle() function randomize the order of the elements in the array, and then returns the elements. On the other hand,array_rand() function picks elements randomly from the array.
  • After running the shuffle() function change the order of the element in the original array. On the other hand,array_rand() function the order of elements in the original array don’t change.
  • The shuffle function removes the keys in the original array. On the other hand, array_rand() function doesn’t change the keys in the original array.

PHP Version Support:

PHP 4, PHP 5, PHP 7, PHP 8

Summary: PHP shuffle() Function

When you want to randomize the position of an array element, you can use shuffle() function which is one of the built-in array functions.

Reference:

https://www.php.net/manual/en/function.shuffle.php