Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Making an array with random repeated values within a range?

I’m making a small function in PHP that, like described in the title, need an array filled with random numbers inside a specified range, the numbers MUST repeat within it. As an example, filling an array with 20 random numbers between 1 and 10 should result in something like this:

Array = [2,5,8,2,8,5,3,9,6,3,4,6,3,1,2,1,2,3,7,1]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This code creates an array ($arr = array();) and then 20 times (the loop) pushes a random value on the end of the array.

The values are generated by random_int function that generates numbers in the given range (inclusively).

<?php

$arr = array();
for ($i = 0; $i < 20; $i++) {
    array_push($arr, random_int(1, 10));
}

The source of randomness is quite good (depending on the system).

If you want such random number array generator as a function, do this:

<?php

function random_ints($count, $min, $max) {
    $arr = array();
    for ($i = 0; $i < $count; $i++) {
        array_push($arr, random_int($min, $max));
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading