3

Possible Duplicate:
Formatting a number with leading zeros in PHP

I have values between 00 - 29 that need to be selected randomly using PHP. I tried to use rand() function, but it gives me 0 - 29. not 00, 01, 02, 03 ... etc.

how to get 00 - 09 instead of 0 - 9 from PHP randomly? thanks.

Community
  • 1
  • 1
Saint Robson
  • 5,475
  • 18
  • 71
  • 118

6 Answers6

13
$random = sprintf("%02f", rand(0,29));

or, as mentioned in the comments:

$random = str_pad(rand(0,29), 2, "0", STR_PAD_LEFT);
John Conde
  • 217,595
  • 99
  • 455
  • 496
1

Create an array like

$array = array('00','01','02','03'....,'29');
echo $array[array_rand($array)];
Justin John
  • 9,223
  • 14
  • 70
  • 129
1

Use str_pad:

$random = str_pad(rand(0, 29), 2, '0', STR_PAD_LEFT);
Giacomo1968
  • 25,759
  • 11
  • 71
  • 103
0

a) Add a "0" if the value ist below 10

b) Use number_format to process the output

rollstuhlfahrer
  • 3,988
  • 9
  • 25
  • 38
0

You can use sprintf to format the number.

$number = rand(0,29);
$number = sprintf("%02d", $number);

Search PHP manual for sprintf

0

You can also use this approach that doesn't depend on additional functions:

$n = rand(0, 29);
if( $n < 10 ) $n = "0" . $n;
Leonel Machava
  • 1,501
  • 11
  • 19
  • Yes this work. But silly when native functions exist. Why code around them? [Be a better PHP developer](http://jason.pureconcepts.net/2012/08/better-php-developer/). – Jason McCreary Aug 08 '12 at 13:51