PHP function array_rand() that randomly selects one or more elements from an array and returns the key name

黄舟
Release: 2023-03-17 08:18:02
Original
2856 people have browsed it

Example

Returns an array containing random key names:

<?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]];
?>
Copy after login

Definition and usage

array_rand() function returns a random key name in the array, or if If the specified function returns more than one key name, an array containing random key names will be returned.

Syntax

array_rand(array,number)
Copy after login
ParametersDescription
array Required. Specifies an array.
numberOptional. Specifies how many random elements to return.

Technical details

As of PHP 5.2.10, the resulting array of keys is no longer
Return value: Returns a random key name in the array, Or if the specified function returns more than one key name, an array containing random key names is returned.
PHP Version: 4+
##Update Log : shuffled.
Since PHP 4.2.0, the random number
generator is automatically seeded.
More examples

Example 1

Return a random key name in the array:

<?php
$a=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
print_r(array_rand($a,1));
?>
Copy after login

Example 2

Returns an array containing random

string key names:

<?php
$a=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
print_r(array_rand($a,2));
?>
Copy after login

Example:

<?php 
$a=array("a"=>"Dog","b"=>"Cat","c"=>"Horse"); 
print_r(array_rand($a,1)); 
?>
Copy after login
Result:


b

The above is the detailed content of PHP function array_rand() that randomly selects one or more elements from an array and returns the key name. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template