jeudi 7 juin 2018

Get five unique random PHP values selected from an array and put them in separate variables

I have an array, for example:

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

I want to select five random and unique values from it and put them in five different variables, for example:

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

I have already found this code below which works for generating the random strings and just displaying them, but the output I want is for getting them in different variables and being able to use them separately.

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




Aucun commentaire:

Enregistrer un commentaire