如何从PHP中的数组中获取随机值
为了从PHP中的数组中获取随机值,代码如下-
示例
<?php$arr = array( "p"=>"150", "q"=>"100", "r"=>"120", "s"=>"110", "t"=>"115", "u"=>"103", "v"=>"105", "w"=>"125" );
echo "Array values ...\n";
echo "Value 1 = " . $arr["p"], "\n";
echo "Value 2 = " . $arr["q"], "\n";
echo "Value 3 = " . $arr["r"], "\n";
echo "Value 4 = " . $arr["s"], "\n";
echo "Value 5 = " . $arr["t"], "\n";
echo "Value 6 = " . $arr["u"], "\n";
echo "Value 7 = " . $arr["v"], "\n";
echo "Value 8 = " . $arr["w"], "\n";
echo "来自数组的随机值 = ".$arr[array_rand($arr)];
?>
输出结果
Array values ...Value 1 = 150
Value 2 = 100
Value 3 = 120
Value 4 = 110
Value 5 = 115
Value 6 = 103
Value 7 = 105
Value 8 = 125
来自数组的随机值 = 110
示例
现在让我们来看另一个示例-
<?php$arr = array( "p"=>"150", "q"=>"100", "r"=>"120", "s"=>"110", "t"=>"115", "u"=>"103", "v"=>"105", "w"=>"125" );
echo "Array values ...\n";
echo "Value 1 = " . $arr["p"], "\n";
echo "Value 2 = " . $arr["q"], "\n";
echo "Value 3 = " . $arr["r"], "\n";
echo "Value 4 = " . $arr["s"], "\n";
echo "Value 5 = " . $arr["t"], "\n";
echo "Value 6 = " . $arr["u"], "\n";
echo "Value 7 = " . $arr["v"], "\n";
echo "Value 8 = " . $arr["w"], "\n";
$res = array_rand($arr, 2);
echo "来自数组的随机值...";
echo $arr[$res[0]]." ".$arr[$res[1]];
?>
输出结果
Array values ...Value 1 = 150
Value 2 = 100
Value 3 = 120
Value 4 = 110
Value 5 = 115
Value 6 = 103
Value 7 = 105
Value 8 = 125
来自数组的随机值...150 115
以上是 如何从PHP中的数组中获取随机值 的全部内容, 来源链接: utcz.com/z/343667.html