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

Time:11-10

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;

?>

CodePudding user response:

Given your use case is for a 'dice roll' I wonder if you would be better off using a cryptographically secure random number generation function like random_int() rather than array_rand(), which is not.

You can then use a for loop for your output as you know in advance how many times you want the loop to run.

$num = 3;

for($i = 0; $i < $num; $i  ){
    print random_int(1,6) . PHP_EOL;
}

CodePudding user response:

The array_rand(arry, n) function returns an array with length n, composed of elements from arry. It looks like you did everything right, however when you print it you only ask for the first 2 random numbers. If you want to print all of the numbers, you will need a for/foreach loop.

foreach($keys as $key) {
    print $key . " ";
}
  • Related