October 23, 2024
Chicago 12, Melborne City, USA
PHP

PHP create a non-repeating range of float numbers using php random generator functions


I am managing a function that can vary a range_pool of numbers with set decimals between them. I would like to find a solution that ensures that these numbers never repeat (create duplicates) when they are generated at the exit of the function.

    `function random($min, $max, $range_pool) {
    
    $decimals = 4;
    
    $collect_range_pool = array();

    for ($i = 0; $i < $range_pool; $i++)
    {
        
        $random_number = mt_rand() / mt_getrandmax();

        $range = $max - $min;

        $random_decimal = $min + $random_number * $range;

        $random_decimal = round($random_decimal, $decimals);

        $collect_range_pool[] = $random_decimal;
    
    }
    
    return $collect_range_pool;
    
}

$generated = random(4.0008, 4.1008, 20);

foreach ($generated as $number)
{
    
    echo $number . '<br>';
    
}`

I am expecting for the number to never repeat.



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video