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.
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
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.