What functions are used in PHP to randomly shuffle an array?

WBOY
Release: 2024-05-01 22:15:02
Original
1094 people have browsed it

The following functions in PHP can shuffle arrays randomly: shuffle() directly changes the order of array elements. array_rand() returns a random key that can rearrange the array order based on the key.

What functions are used in PHP to randomly shuffle an array?

Functions for randomly shuffling arrays in PHP

In PHP, there are several functions that can be used to randomly shuffle arrays , changing the order of its elements. These functions include:

1. shuffle()

##shuffle() The function directly shuffles the incoming array and changes its internal The order of the elements.

<?php
$arr = [1, 2, 3, 4, 5];
shuffle($arr);
print_r($arr); // 输出洗牌后的数组
?>
Copy after login

2. array_rand()

array_rand() The function will return the specified number of random keys in the array, which can be rearranged according to these keys Array order.

<?php
$arr = [1, 2, 3, 4, 5];
$keys = array_rand($arr, 3); // 随机返回 3 个键
$sortedArr = [];
foreach ($keys as $key) {
    $sortedArr[] = $arr[$key];
}
print_r($sortedArr); // 输出重新排列后的数组
?>
Copy after login

Practical case:

Suppose you have a list of student names and need to be randomly assigned to different classes. You can use the following code:

<?php
$students = ['John', 'Mary', 'Bob', 'Alice', 'Tom'];
shuffle($students);
// 将学生分成 2 个班级
$class1 = array_slice($students, 0, 3);
$class2 = array_slice($students, 3);
print_r($class1); // 输出第一个班级中的学生
print_r($class2); // 输出第二个班级中的学生
?>
Copy after login

The above is the detailed content of What functions are used in PHP to randomly shuffle an array?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!