The shuffle () function of PHP is used to analyze several random elements in the array.

Source: Internet
Author: User

The shuffle () function of PHP is used 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']. '<br/>';} $ 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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.