How to Randomly Shuffle Arrays in PHP: shuffle() and array_rand() Explained

Learn how to randomize array order in PHP using built-in functions like shuffle() and array_rand(), with clear code examples and a practical scenario of assigning students to classes, plus step-by-step explanations of each method’s behavior and usage.

php Courses
php Courses
php Courses
How to Randomly Shuffle Arrays in PHP: shuffle() and array_rand() Explained

In PHP, several built-in functions can randomize the order of an array’s elements.

shuffle()

The shuffle() function shuffles an array in place, directly modifying the original array.

<?php
$arr = [1, 2, 3, 4, 5];
shuffle($arr);
print_r($arr); // outputs the shuffled array
?>

array_rand()

array_rand()

returns one or more random keys from an array; these keys can then be used to reorder the array.

<?php
$arr = [1, 2, 3, 4, 5];
$keys = array_rand($arr, 3); // returns 3 random keys
$sortedArr = [];
foreach ($keys as $key) {
    $sortedArr[] = $arr[$key];
}
print_r($sortedArr); // outputs the reordered array
?>

Practical example

Suppose you have a list of student names that need to be randomly assigned to two classes. The following code shuffles the list and then splits it into two groups.

<?php
$students = ['John', 'Mary', 'Bob', 'Alice', 'Tom'];
shuffle($students);
// Divide students into two classes
$class1 = array_slice($students, 0, 3);
$class2 = array_slice($students, 3);
print_r($class1); // first class
print_r($class2); // second class
?>
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.

PHPArrayrandomizationShufflearray_rand
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.