How To Shuffle/Randomize Array in PHP – POFTUT

How To Shuffle/Randomize Array in PHP


There are different ways to randomly select elements of an array in PHP. But recurring elements are biggest problem most of them. Here the clean and PHP library supported solution for this. We will use shuffle() function which will change the positions of the given array.

Shuffle Example

shuffle() function accept only single parameter which is the array we want to shuffle. shuffle() function will return shuffled array. In this example we will create an array which is consist of numbers from 1 to 20 in a sequential way. Then we will shuffle() this array and print to the screen.

<?php
$numbers = range(1, 20);
shuffle($numbers);
foreach ($numbers as $number) {
    echo "$number ";
}
?>

Here shuffle function accepts an array and changes the keys of the array in place.

Shuffle Example
Shuffle Example

As we can see that ordered array will be shuffeled and printed in a random way  like 15,1,10,12,8,…

LEARN MORE  How To List MySQL Database Users?

Leave a Comment