PHP Functions for Randomly Shuffling Arrays

This article explains PHP’s built‑in functions for randomly shuffling arrays—shuffle() and array_rand()—provides code examples for each, and demonstrates a practical case of assigning students to classes using these functions, followed by links to additional programming learning resources.

php Courses
php Courses
php Courses
PHP Functions for Randomly Shuffling Arrays

In PHP, there are several functions that can randomly shuffle an array, changing the order of its elements.

1. shuffle()

The shuffle() function directly shuffles the given array, modifying its internal element order.

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

2. array_rand()

The array_rand() function returns a specified number of random keys from the array; using these keys you can reorder the array.

<?php
$arr = [1, 2, 3, 4, 5];
$keys = array_rand($arr, 3); // randomly return 3 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 different classes. The following code demonstrates how to achieve this:

<?php
$students = ['John', 'Mary', 'Bob', 'Alice', 'Tom'];
shuffle($students);
// Divide students into 2 classes
$class1 = array_slice($students, 0, 3);
$class2 = array_slice($students, 3);
print_r($class1); // outputs students in the first class
print_r($class2); // outputs students in the second class
?>

Java learning materials

C language learning materials

Frontend learning materials

C++ learning materials

PHP learning materials

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.

BackendPHParray_randArray Shuffleshuffle()
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.