John Davidson

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

0 comments
Message:


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;

?>


My Answer:
You are on the right track with using the array_rand function, but you need to loop through the keys array to get all the random elements. Here is an updated version of your code that should work:

php

if ($argc < 2) {
print "You have to write at least one parameter" . PHP_EOL;
exit(1);
}

$num = $argv[1];
$diceNumbers = [1, 2, 3, 4, 5, 6];
$keys = array_rand($diceNumbers, $num);

foreach ($keys as $key) {
print $diceNumbers[$key] . " ";
}

print PHP_EOL;

?>


With this code, you should be able to generate the specified number of random elements from the diceNumbers array. Just make sure to pass the desired number as a command line argument when running the script.

Rate this post

4 of 5 based on 9381 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us