Home > Article > Backend Development > How to use the php shuffle() function to take several random elements from an array
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]['name'].'<br />'; } $i++; }
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!