PHP array_rand() 函数

PHP 教程 · 2019-01-22 12:12:30

实例

返回一个包含随机键名的数组:

<?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]]; ?>

定义和用法

array_rand() 函数返回数组中的一个随机键名,或者如果指定函数返回键名不只一个,则返回一个包含随机键名的数组。

语法


array_rand(array,number)

参数 描述
array 必需。规定数组。
number 可选。规定返回多少个随机的元素。

技术细节

返回值: 返回数组中的一个随机键名,或者如果指定函数返回键名不只一个,则返回一个包含随机键名的数组。
PHP 版本: 4+
更新日志: 自 PHP 5.2.10 起,键名的结果数组不再ay of keys is no longer shuffled。

自 PHP 4.2.0 起,随机数生成器会自动播种。

更多实例

实例 1

返回数组中的一个随机键名:

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

实例 2

返回一个包含随机字符串键名的数组:

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

点击查看所有 PHP 教程 文章: https://codercto.com/courses/l/5.html

查看所有标签

Algorithms in C (Computer Science Series)

Algorithms in C (Computer Science Series)

Robert Sedgewick / Addison-Wesley Professional / 1990-01-11 / USD 59.99

This new version of the best-selling book, Algorithms, SecondEdition, provides a comprehensive collection of algorithmsimplemented in C. A variety of algorithms are described in eachofthe following ar......一起来看看 《Algorithms in C (Computer Science Series)》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具