Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

prevent Random PHP generator from including zeros

Tags:

php

random

I have a php script that creates a random 10 digit order number:

// Assign order number length
$digits = 10;

// Create random order number to be stored with this order
$order_number = rand(pow(10, $digits-1), pow(10, $digits)-1);

How do I prevent this from ever including the digit zero 0 in the random 10 digit number? Thanks in advance!

like image 303
Mitch Evans Avatar asked Dec 19 '22 23:12

Mitch Evans


1 Answers

You can do fancy base conversions, but in the end, the most straightforward way is to just get a string:

function random_string($count, $available) {
    $result = '';
    $max = strlen($available) - 1;

    for($i = 0; $i < $count; $i++) {
        $result .= $available[rand(0, $max)];
    }

    return $result;
}

…
$order_number = random_string($digits, '123456789');
like image 120
Ry- Avatar answered Jan 09 '23 15:01

Ry-