How to generate a random array in PHP
This tutorial will teach us how to generate a random array in PHP. This tutorial contains various ways to generate a random array. Hope this tutorial is helpful to you. Let’s get started.
Generate Random Array in PHP
An array is a linear data structure. In this arrangement of elements such that elements are of the same type and memory allocation is contiguous. To generate a random array in PHP we will see two methods.
First, we will generate a random number between 0 to 100 and store it in one variable. Then we will use the shuffle() function in PHP to shuffle the generated random number. Now we will use the array_slice() method in PHP, and finally, generate a random array.
Below is the given syntax to perform our task:
array_slice(array, starting point, length of an array, preserve)
Now let’s look at our code:
<!DOCTYPE html> <html> <body> <?php $random_number_range = range(0, 100); shuffle($random_number_range ); $random_number_array_generated = array_slice($random_number_range ,0,10); print_r($random_number_array_generated); ?> </body> </html>
OUTPUT: Array ( [0] => 53 [1] => 99 [2] => 54 [3] => 52 [4] => 21 [5] => 94 [6] => 11 [7] => 38 [8] => 8 [9] => 97 )
Another way to generate a random array in PHP. Here in this we first declare a variable of a particular size. Then we create a variable for storing an array value in it. We use a for loop to iterate for every element in an array and then we generate a random array value and assign it to each variable.
Syntax:
array_rand(array, number) It basically generate an array for random keys and returns an array.
<!DOCTYPE html> <html> <body> <?php $numberOfItems = 10; $numbers = range(0, $numberOfItems-1); $rands = array(); for ($i=0; $i < $numberOfItems; $i++) { $ok = false; while (!$ok) { $x = array_rand($numbers); $ok = !in_array($numbers[$x], $rands) && $numbers[$x] != $i; } $rands[$i] = $numbers[$x]; unset($numbers[$x]); } var_dump($rands); ?> </body> </html>
OUTPUT: array(10) { [0]=> int(1) [1]=> int(3) [2]=> int(8) [3]=> int(0) [4]=> int(2) [5]=> int(4) [6]=> int(7) [7]=> int(5) [8]=> int(9) [9]=> int(6) }
Hope you liked this video. Happy Learning!!!!!
Leave a Reply