Using PHP shuffle() to Randomly Rearrange Array Elements

This article explains PHP's shuffle() function, detailing its syntax, behavior of modifying the original array, return value, usage with indexed and associative arrays, and provides multiple code examples illustrating how to randomize array elements.

php Courses
php Courses
php Courses
Using PHP shuffle() to Randomly Rearrange Array Elements

In PHP programming, the shuffle() function is used to randomize the order of elements in an array.

The function signature is: shuffle(array &$array) : bool It accepts an array by reference, shuffles its elements in place, and returns a boolean indicating success.

Example with an indexed array:

// Declare and initialize an array
$myArray = array("Apple", "Banana", "Cherry", "Durian");

// Print original array
echo "Original array:";
print_r($myArray);

// Shuffle the array
shuffle($myArray);

// Print shuffled array
echo "Shuffled array:";
print_r($myArray);

The output shows the original order followed by a randomly reordered array.

The function also returns true on success, which can be used for conditional logic.

Note that shuffle() works only with indexed arrays; when applied to an associative array, it reindexes the keys to consecutive numbers. Example:

// Declare and initialize an associative array
$myArray = array("a" => "Apple", "b" => "Banana", "c" => "Cherry");

// Print original array
echo "Original array:";
print_r($myArray);

// Shuffle the array
shuffle($myArray);

// Print shuffled array
echo "Shuffled array:";
print_r($myArray);

After shuffling, the keys are reset to 0, 1, 2, demonstrating the reindexing behavior.

Overall, shuffle() is a practical PHP function for randomizing array elements, and the provided examples help developers understand its usage.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PHPArrayTutorialrandomizationShuffle
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

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.