English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

PHP Basic Tutorial

PHP Advanced Tutorial

PHP & MySQL

PHP Reference Manual

PHP array_rand() Function Usage and Example

PHP Array Function Manual

The PHP array_rand() function randomly selects one or more units from an array

Syntax

array_rand($input[, $num_req]);

Definition and Usage

Extract one or more random units from the array and return one or more keys of the random entry. It uses a pseudo-random number generation algorithm, so it is not suitable for cryptographic scenarios,

Parameter

Serial NumberParameters and Description
1

array (required)

It specifies an array.

2

num_req (optional)

It specifies the number of entries to be selected - If not specified, the default is1.

Return Value

If only one is taken out, array_rand() returns the key name of the random unit. Otherwise, it returns an array containing random key names. After that, you can get the random value of the array according to the random key. If the number of items taken out exceeds the length of the array, it will cause an E_WARNING error and return NULL.

Online Example

Extract a record randomly from an array

<?php
   $input = array("a"=>"banana","b"=>"apple","c"=>"orange");
   
   print_r(array_rand($input));
?>
Test and see‹/›

This will produce the following results, which will be different each time the script is executed-

b

PHP Array Function Manual