PHP randomly selects one or more elements from an array to return the key name of the function Array_rand ()

Source: Internet
Author: User

Instance

Returns an array that contains a random key name:

<?php$a=array ("Red", "green", "blue", "yellow", "brown"), $random _keys=array_rand ($a, 3), echo $a [$random _keys[0]]. " <br> "echo $a [$random _keys[1]]." <br> "echo $a [$random _keys[2]];? >

Definition and usage

The Array_rand () function returns a random key name in the array, or returns an array containing a random key name if the specified function returns more than one key name.

Grammar

Array_rand (Array,number)
Parameters Describe
Array Necessary. Specifies the array.
Number Optional. Specifies how many random elements are returned.

Technical details

return value: Returns a random key name in the array, or returns an array containing a random key name if the specified function returns more than one key name.
php version: 4+
update log: since PHP 5.2.10, the result array of the key name is no longer ay of the keys is no longer shuffled.

Since PHP 4.2.0, the random number generator will be seeded automatically.

More examples

Example 1

Returns a random key name in the array:

<?php$a=array ("A" = "red", "b" = "green", "c" = "Blue", "D" and "Yellow");p Rint_r (Array_rand ($a, 1));? >

Example 2

Returns an array containing a random string key name:

<?php$a=array ("A" = "red", "b" = "green", "c" = "Blue", "D" and "Yellow");p Rint_r (Array_rand ($a, 2));? >

Example:

<?php $a =array ("a" = "Dog", "b" = "Cat", "C" and "Horse"); Print_r (Array_rand ($a, 1));?>

Results:

B

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.