从数组中选择五个唯一的随机PHP值,并将它们放在单独的变量中

时间:2018-06-07 14:06:42

标签: php arrays string random

我有一个数组,例如:

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

4 个答案:

答案 0 :(得分:7)

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

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

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

文档:shuffle()list()

答案 1 :(得分:1)

使用此:

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

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);

  array_push($random, $selected);
}

var_dump($random);
  • 我已经修复了你的循环逻辑,所以它现在显示5个项而不是4个。
  • 我使用short syntax来定义一个需要5.4或更高版本的数组。

<强>输出

array(5) {
  [0]=>
  string(3) "ggg"
  [1]=>
  string(3) "fff"
  [2]=>
  string(3) "eee"
  [3]=>
  string(3) "ddd"
  [4]=>
  string(3) "ccc"
}

直播示例

Repl

答案 2 :(得分:0)

这应该有效:

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

    $tmp = $arr;
    array_rand($tmp);

    $one = $tmp[0];
    $two = $tmp[1];
    ...

记住,如果$ tmp [n]中的值实际存在

,它将不会显示

答案 3 :(得分:0)

您可以使用PHP的shuffle函数随机化数组中元素的顺序,然后获取第一个元素。

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

$randomArray = array_slice($randomArray, 0, 5);

$randomArray[0]; //1st element
$randomArray[1]; //2nd element
$randomArray[2]; //3rd element...