mardi 9 novembre 2021

How to get a specific number of random elements from an array in php?

So, I,been trying to write a code for a "Dice generator" and I want it to generate random numbers (from 1-6) a x numbers of times. The x number of times is given as a parameter by the user through the terminal, with this "$argc argv" function, but this is not really important.

What I want to know is: how do I generate random values x number of times?

FOR EXAMPLE:

User input: 4

Output: 5 3 6 8

User input: 3

Output: 5 1 2

This is what I am trying to write. I used the array_rand function with the array as a parameter, and the number of times I want as the second parameter, but It does not work! What am I not getting here?

<?php

if ($argc < 2) {
    print "You have to write at least one parameter" .PHP_EOL;
    exit(1);
}
//This is the variable that corresponds to the number of times the user will give on the Terminal as a parameter.
//$randoms = $argv[1];
$num = 3;
$diceNumbers = [1, 2, 3, 4, 5, 6];
$keys = array_rand($diceNumbers, $num);

print $diceNumbers[$keys[0]]." ".$diceNumbers[$keys[1]] .PHP_EOL;

?>



Aucun commentaire:

Enregistrer un commentaire