Signup/Sign In
PUBLISHED ON: AUGUST 6, 2021

How to randomize the order of an array in PHP?

Answer: Using shuffle() function

We can randomize the order of the elements in an array using the using shuffle() function. This function assigns the new keys for the elements within the array and generates an array having random values.

Example: Randomizing the array

In the given example, we have randomized the elements of an array using the shuffle() function.

<!DOCTYPE html>  
<html> 
<head>
	<title>Randomizing the order of an array </title>
</head> 
<body>  
	<?php
		$arr = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

		shuffle($arr);
		foreach ($arr as $value){
		    echo "$value" . "<br>";
		}
	?>
</body>  
</html>  


7
4
3
8
2
5
6
1
9
10

Using array_rand() function

We can also randomize the array elements using the array_rand() function. This function returns the random key from an array.

It also returns more than one key by specifying it within the function. This function takes two parameters first one is an array and the second one is a number that is used to specify the number of keys we get in return.

Example: Randomizing the elements of an array

In the given example, we get the 5 random array elements using array_rand() function.

<!DOCTYPE html>  
<html> 
<head>
	<title>Randomizing the order of an array </title>
</head> 
<body>  
	<?php
		$arr = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
		$new_arr = array_rand($arr, 5);
		var_dump($new_arr);
	?>
</body>  
</html>  


array(5) { [0]=> int(0) [1]=> int(1) [2]=> int(2) [3]=> int(4) [4]=> int(8) }

Conclusion

In this lesson, we have learned how to randomize the elements of an array in PHP. Here we have used two methods to randomize the elements of an array. First, we have used the shuffle() function. This function shuffles all the elements of an array. Then we have used the array_rand() function. This function returns a random key from the given element. Using this function, we can get a single random key, or we can also specify the number of random keys we want to get from the array.



About the author:
I am the founder of Studytonight. I like writing content about C/C++, DBMS, Java, Docker, general How-tos, Linux, PHP, Java, Go lang, Cloud, and Web development. I have 10 years of diverse experience in software development.