php - 數組中隨機顯示一個?
PHP中文网
PHP中文网 2017-04-11 10:37:34
[PHP讨论组]
 $arry = array('A','B','C','D');
$result = array_rand($arry,2);
foreach ($result as $val) 
{
echo $arry["$val"].""; 
}

請問一下 這樣會隨機產生2組 ABCD的組合 例如BC DC AB等等
但我想顯示的是只要顯示一個就好了 隨機從數組中顯示A或B或C或D
請問這樣怎麼做?
我把2改1後就失敗了

PHP中文网
PHP中文网

认证0级讲师

全部回复(3)
PHPz

mixed array_rand ( array $array [, int $num = 1 ] )
# Picks one or more random entries out of an array, and returns the key (or keys) of the random entries. It uses a pseudo random number generator that is not suitable for cryptographic purposes.

会随机返回指定数组中的键,根据需求$num会返回一个键 或 以数组的形式返回多个键。

如果你有数组

<?php
$arry = array('A','B','C','D');

现在想每次随机输出数组中的一个元素,则可以采用以下方式获取:

<?php
$arry = array('A','B','C','D');
$rand_key = array_rand($array, 1);
echo $array[$rand_key];

以此同理可以实现其他的随机元素键并获取数组的随机元素。

PHPz
$array = array('A','B','C','D');
$newArray = $array;
shuffle($newArray);
echo $newArray[0];
阿神

Picks one or more random entries out of an array, and returns the key
(or keys) of the random entries. It uses a pseudo random number
generator that is not suitable for cryptographic purposes.

如果第二个参数为1或者没有时, 返回的并不是数组, 而只是一个数字

    $result = array_rand($arry,2); // 是一个**数组** 如[1,2,3]
    $result = array_rand($arry,1); // 只是一个**数字** 如 1, 并不是[1]
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号