如何在包含所有字符串元素的数组上应用 rand() 或其他一些内置函数,以便随机 select 一个字符串?

How to apply rand() or some other built-in function on an array that contains all string elements in order to randomly select a string?

我有以下数组:

$family = array("Amit", "Suresh", "Vinit", "Somesh", "Sagar", "Shriram");

现在我想从上面的数组中随机 select 一个名字。

我应该怎么做?

我知道 rand() 函数。即使我尝试了 rand($family); 但它给了我如下警告:

警告:rand() 需要 2 个参数,其中 1 个在第 7 行 /var/www/project/index.php

中给出

它要求第二个参数。

所以请有人帮我 select 从包含所有字符串元素的数组中随机输入一个字符串。

谢谢。

试试这个

$num = rand(0, count($family)-1);
$family[$num]

先阅读文档,示例中有您要查找的确切功能

http://php.net/manual/en/function.array-rand.php

<?php
$input = array("Neo", "Morpheus", "Trinity", "Cypher", "Tank");
$rand_keys = array_rand($input, 2);
echo $input[$rand_keys[0]] . "\n";
echo $input[$rand_keys[1]] . "\n";
?>
// Count the elements    
$count = count($family);
// decrement the count by 1
$count--;
// echo a random item from the array
echo $family[rand(0, $count)];
$num = rand(0, count($family)-1);
$family[$num]

rand() 函数接受零个或两个参数。如果参数为零,它将产生一个介于 0 和 getrandmax() 之间的伪随机整数。否则它需要两个整数参数 minmax 并将产生一个介于 minmax 之间的伪随机整数。

正如@Yurich 指出的,这可能是您想要的。

$num = rand(0, count($family-1));
$family[$num]

说明:rand(0, count($family-1)) 将生成一个介于 0 和数组中元素数减一之间的随机整数。此数字将存储在 $num 中,之后用于访问 "random" 索引处的数组。

rand() 不是一个好的选择,对于 PHP7 有更好的选择。见下文:

$family = array("Amit", "Suresh", "Vinit", "Somesh", "Sagar", "Shriram");

if(version_compare(PHP_VERSION,'7.0.0', '<') ) {
    // for PHP < 7
    $rand_name = $family[mt_rand(0, count($family) - 1)];
} else {
    // for PHP >= 7
    $rand_name = $family[random_int(0, count($family) - 1)];
}