The shuffle () function of PHP analyzes several random elements in the array and shuffle the array. The shuffle () function of PHP analyzes several random elements in an array. This document describes how to shuffle () function of PHP to obtain several random elements in an array. We will share with you the shuffle () function of PHP to analyze several random elements in the array.
This example describes how to use the shuffle () function of PHP to obtain several random elements of an array. We will share this with you for your reference. The details are as follows:
Sometimes we need to obtain several random elements in the array (for example, the random recommendation function). how can we implement PHP? A simple solution is to use the shuffle () function provided by PHP. The following is a simple example:
$ Data [] = array ("name" => "", "rank" => "40 "); $ data [] = array ("name" => "blog", "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'].'
';}$ I ++ ;}
Shuffle ()
The shuffle () function sorts the elements in the array in random order. If yes, TRUE is returned. otherwise, FALSE is returned. This function assigns a new key name to the unit in the array. This will delete the original key name, not just the reorder.
If the input is an associated array, you will find that the key names of the associated array are lost. By the way, the solution is as follows:
// Shuffle_assoc ($ array) {$ randomized_keys = array_rand ($ array, count ($ array); foreach ($ randomized_keys as $ current_key) {$ output [$ current_key] = $ array [$ current_key];} return $ output ;}
In addition, php also provides a function to randomly extract values from an array: array_rand (). The calling format is as follows: array_rand (array, number of extracted elements ); of course, to support two-dimensional arrays, you need to encapsulate them before using them. However, the preceding program supports two-dimensional arrays.