How to randomly extract the value of n data in an array in PHP-Array_rand ()?

Source: Internet
Author: User

How do you randomly extract the values of n data in an array in PHP?

Best Answer

Array_rand () is useful when you want to remove one or more random cells from an array. It accepts input as an input array and an optional parameter, Num_req, indicating how many units you want to remove-if not specified, the default is 1. If you only take one, Array_rand () returns the key name of a random cell, or returns an array containing the random key name. This allows you to randomly remove the key names and values from the array.

As shown in the following example:

<?php$input = Array ("Neo", "Morpheus", "Trinity", "Cypher", "Tank"), $rand _keys = Array_rand ($input, 2);p rint $input [$ Rand_keys[0]]. "\ n";p rint $input [$rand _keys[1]]. "\ n";

Output:

Trinitycypher

" Attention "

When Num_req is 1 o'clock, returns non-array data , and when Num_req >=2, returns the array data , so if the number of fetching is not determined to be 1, it is recommended to convert the arrays uniformly as follows:

$num _req = max (1, $num _req), $num _req = min ($num _req, Count ($input)), $rand _keys = (array) array_rand ($input, $num _req);

How to randomly extract the value of n data in an array in PHP-Array_rand ()?

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.