Cla*_*ado 1 php arrays string random
我有一个数组,例如:
array("aaa", "bbb", "ccc", "ddd", "eee", "fff", "ggg");
Run Code Online (Sandbox Code Playgroud)
我想从中选择五个随机和唯一的值,并将它们放在五个不同的变量中,例如:
$one = "ccc";
$two = "aaa";
$three = "bbb";
$four = "ggg";
$five = "ddd";
Run Code Online (Sandbox Code Playgroud)
我已经在下面找到了这个代码,它可以生成随机字符串并只显示它们,但我想要的输出是将它们放在不同的变量中并且能够单独使用它们.
<?php
$arr = $arr_history = array("aaa", "bbb", "ccc", "ddd", "eee", "fff", "ggg");
for ( $i = 1; $i < 5; $i++ )
{
// If the history array is empty, re-populate it.
if ( empty($arr_history) )
$arr_history = $arr;
// Randomize the array.
array_rand($arr_history);
// Select the last value from the array.
$selected = array_pop($arr_history);
// Echo the selected value.
echo $selected . PHP_EOL;
}
Run Code Online (Sandbox Code Playgroud)
您可以shuffle使用数组并使用它list来分配值
$arr = array("aaa", "bbb", "ccc", "ddd", "eee", "fff", "ggg");
shuffle( $arr );
list($one, $two, $three, $four, $five) = $arr;
Run Code Online (Sandbox Code Playgroud)