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