Backend Development 3 min read

PHP shuffle() Function: Randomly Reordering Arrays with Detailed Examples

This article explains the PHP shuffle() function, its syntax, parameters, return values, and demonstrates three practical examples showing how to randomize indexed and associative arrays, highlighting the effect on array keys and values after shuffling.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
PHP shuffle() Function: Randomly Reordering Arrays with Detailed Examples

The shuffle() function in PHP randomly rearranges the order of elements in an array.

Syntax:

bool shuffle (array &$array)

It takes a single argument – the array to be shuffled – passed by reference, and returns TRUE on success or FALSE on failure.

Example 1 – Shuffling a numeric indexed array:

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

This creates an array of numbers from 1 to 20, shuffles it, and prints the numbers in their new random order.

Example 2 – Shuffling a simple indexed array of strings:

<?php $my_array = array("red", "green", "blue", "yellow", "purple"); shuffle($my_array); print_r($my_array); ?>

After shuffling, the array retains numeric indexes (0, 1, 2, …) but the values appear in a random sequence.

Example 3 – Shuffling an associative array:

<?php $my_array = array( "a" => "red", "b" => "green", "c" => "blue", "d" => "yellow", "e" => "purple" ); shuffle($my_array); print_r($my_array); ?>

When an associative array is shuffled, its original keys are discarded and the result becomes a re‑indexed numeric array, with only the values shuffled.

These examples illustrate that shuffle() randomizes the order of elements, but for associative arrays the keys are lost, turning them into indexed arrays.

backendarrayTutorialShuffleRandom
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.