In this article, you will learn how to rearrange or randomly arrange the elements of an array. The shuffle() function performs the action. Look at the examples and syntax below.
Note: In the case of an associative array, the shuffle function assigns new keys to the values and removes the old ones.
What is the syntax of the shuffle() function in PHP?
shuffle(array)
Parameter | Details |
---|---|
array | The array to shuffle – Required |
Examples of the shuffle() function
Example 1. Randomize/Rearrange the associative array elements.
<?php
$arr=array("a"=>"1","b"=>"2","c"=>"Pak","d"=>"Ch","e"=>"Turk");
shuffle($arr);
print_r($arr);
?>
Example 2. Randomize/Rearrange the indexed array elements.
<?php
$arr= array("R","G","B","Y","P");
shuffle($arr);
print_r($arr);
?>