PHP program to generate random phone number

Posted on

Problem

I created a PHP program to generate random phone numbers. A valid phone number:

  • must be exactly 11 digits in length, and
  • must start with any of the values mentioned in the $a array, and

How can I improve it? Specifically, how can I improve

  • its readability, and
  • its performance, assuming I want to generate millions of results.
<?php
      function rand_(){
    $digits_needed=7;

    $random_number=''; // set up a blank string

    $count=0;

    while ( $count < $digits_needed ) {
        $random_digit = mt_rand(0, 8);
        $random_number .= $random_digit;
        $count++;
    }

    return $random_number;

    }

    $a=array('0812', '0813'  ,'0814' ,'0815' ,'0816' ,'0817' ,'0818','0819','0909','0908');
        $i=0;
        while($i<21){
            $website = $a[mt_rand(0, count($a) - 1)];
           print $website . rand_().'<br>';
           $i++;
        }

Solution

  1. Use accurate and meaningful names for functions and variable to improve readability.
  2. Condense your numeric loop conditions into a for loop versus while loop.
  3. Avoid declaring single-use variables.
  4. Make functions versatile by passing output-altering arguments with the call.
  5. Write default argument values when possible/reasonable so that, in some cases, no arguments need to be passed for the most common scenario.
  6. Avoid counting a static array in a loop. If you need to count it, count it once before entering the loop and reference the count variable.
  7. If you prefer mt_rand‘s randomness, use it in place of my array_rand() call below, but obey #6 about counting.
  8. Obey PSR Coding Standards. Spacing and tabbing don’t improve performance, but they sure make your code easier to read.

Some suggested applications of my generalized advice:

Code: (Demo)

function randomNumberSequence($requiredLength = 7, $highestDigit = 8) {
    $sequence = '';
    for ($i = 0; $i < $requiredLength; ++$i) {
        $sequence .= mt_rand(0, $highestDigit);
    }
    return $sequence;
}

$numberPrefixes = ['0812', '0813', '0814', '0815', '0816', '0817', '0818', '0819', '0909', '0908'];
for ($i = 0; $i < 21; ++$i) {
    echo $numberPrefixes[array_rand($numberPrefixes)] , randomNumberSequence() , "n";
}

Possible Output:

08161776623
08157676208
08188430651
08187765326
08176077144
09087477073
08127415352
08191681262
08168828747
08195023836
08198008111
09096738254
08162004285
08166810731
08130133373
09093214002
08154125422
08160702315
08143817877
08194806336
08133183466

Leave a Reply

Your email address will not be published. Required fields are marked *