How to use the php shuffle() function to take several random elements from an array

怪我咯
Release: 2023-03-13 21:54:02
Original
1382 people have browsed it

This article mainly introduces the PHP functionshuffle() method to get several random elements from an array. It analyzes the function, definition and usage of the shuffle function in detail in the form of examples. Related Notes, friends in need can refer to the following

The example of this article describes how the PHP function shuffle() takes several random elements from an array. Share it with everyone for your reference, the details are as follows:

Sometimes we need to take several random elements in the array (such as making random recommendation functions), so how to implement it in PHP? A relatively simple solution is to use the shuffle() function that comes with PHP.

shuffle()

shuffle() function rearranges the elements in the array in random order. Returns TRUE if successful, FALSE otherwise. This function assigns new key names to the cells in the array, which will deletethe original key names instead of just reordering them.

Here is a simple example:

$data[] = array(
    "name" => "脚本之家",
    "rank" => "40"
);
$data[] = array(
    "name" => "博客园",
    "rank" => "50"
);
$data[] = array(
    "name" => "CSDN",
    "rank" => "60"
);
$data[] = array(
    "name" => "ITEYE",
    "rank" => "50"
);
shuffle($data);
$i = 0;
foreach($data as $key =>$value ){
    if($i < 2) {
        echo $data[$key][&#39;name&#39;].&#39;<br />&#39;;
    }
    $i++;
}
Copy after login

The above is the detailed content of How to use the php shuffle() function to take several random elements from 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!