php

PHP shuffle() Function

shuffle() in PHP is used to shuffle the values in an array randomly. If only shuffles values, but not keys.

Syntax:

shuffle(array_input)

Parameter:
array_input is the array
Let’s see examples to understand this concept better.

Example 1:

In this example, we will create an array with four values: ‘’lotus’,’lilly’,’rose’,’jasmine’.

Let’s shuffle the values present in the array.

<?php

//create 4 values in an array
$Flower=array(‘lotus’,’lilly’,’rose’,’jasmine’);

echo “Actual Array:;
print_r($Flower);

//shuffle the array
shuffle($Flower);

echo “Shuffled Array:;
print_r($Flower);

?>

Output:

The values in the array were shuffled. The first value is rose, second is lilly, third is jasmine, and the last value in the shuffled array is lotus.

Example 2:

In this example, we will create an array with four key-values: 1=>’lotus’,2=>’lilly’,5=>’rose’,0=>’jasmine’.

Let’s shuffle the values present in the array.

<?php

//create 4 key-values in an array
$Flower=array(1=>'lotus',2=>'lilly',5=>'rose',0=>'jasmine');

echo "Actual Array: ";
print_r($Flower);

//shuffle the array
shuffle($Flower);

echo "Shuffled Array: ";
print_r($Flower);

?>

Output:

The values in the array were shuffled. First value is lotus, second is rose, third is lilly, and the last value in the shuffled array is jasmine.

Example 3:

It is also possible to shuffle the nested arrays inside the array. In this case, the arrays will be shuffled. But the values in each nested array will not be shuffled.

<?php

//create 2 arrays in an array
$Flower=array($flowers=array('lotus','lilly','jasmine','rose'),$veg=array('carrot','onion','chillies'));


echo "Actual Array: ";
print_r($Flower);

//shuffle the array
shuffle($Flower);

echo "Shuffled Array: ";
print_r($Flower);

?>

Output:

As we see, the first two nested arrays are shuffled. But the elements inside each array remain the same.

Conclusion

In this article, we saw how to shuffle the values present in the array or nested arrays using the shuffle() function in PHP. It takes array input as a parameter and shuffles the values randomly. You may notice that in nested arrays, the arrays will shuffle. But the values in each nested array will not be shuffled.

About the author

Gottumukkala Sravan Kumar

B tech-hon's in Information Technology; Known programming languages - Python, R , PHP MySQL; Published 500+ articles on computer science domain