首页 > 解决方案 > 从数组中选择五个唯一的随机 PHP 值并将它们放入单独的变量中

问题描述

我有一个数组,例如:

 array("aaa", "bbb", "ccc", "ddd", "eee", "fff", "ggg");

我想从中选择五个随机且唯一的值,并将它们放入五个不同的变量中,例如:

    $one = "ccc"; 
    $two = "aaa";
    $three = "bbb"; 
    $four = "ggg";
    $five = "ddd";

我已经在下面找到了这段代码,它可用于生成随机字符串并仅显示它们,但我想要的输出是将它们放入不同的变量中并能够单独使用它们。

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

标签: phparraysstringrandom

解决方案


您可以shuffle数组并使用list来分配值

$arr = array("aaa", "bbb", "ccc", "ddd", "eee", "fff", "ggg");

shuffle( $arr );
list($one, $two, $three, $four, $five) = $arr;

文档:shuffle() , list()


推荐阅读