1

Hi am using the following to gen a 4 char numeric

 $this->pin = rand(0000,9999)

however if the result is 0435 the leading zero is omitted. How can I keep the leading zero in the result?

is_numeric
  • 187
  • 2
  • 13
  • 6
    Numbers don't have leading zeroes, numbers formatted as strings have leading zeroes `$this->pin = sprint('%04d', rand(0000,9999));` though you're better formatting just at the point where you want to display – Mark Baker Aug 20 '14 at 18:16
  • http://php.net/manual/en/function.str-pad.php – PeeHaa Aug 20 '14 at 18:18
  • 1
    Just a point I always like to submit when seeing rand, use mt_rand for a better random value. – Travis Weston Aug 20 '14 at 18:29

2 Answers2

4

You can also:

$number = rand(0,9999);
$this->pin = str_pad($number,4,0,STR_PAD_LEFT);
Rasclatt
  • 12,498
  • 3
  • 25
  • 33
0

An integer is not a string, so you can't have a leading zero! :-P However you can do:

function zfill($str,$n){
  $ret = $str;
  while(strlen($ret)<$n){
    $ret = '0'.$ret;
  }
  return $ret;
}

$this->pin = zfill($this->pin, 4);