Here is an easier approach - I like to use, mt_rand() which is arguably better than rand()
mt_srand((double)microtime()*1000000);
$randomNumber = mt_rand(0,9999);
When you call the mt_rand() function (or the rand() function), you can specify a lower and upper limit to the number it will produce.
When you output the number, you need to use printf() to preserve the number of digits when the random number is less than 1000.
mt_srand((double)microtime()*1000000);
$randomNumber = mt_rand(0,9999);
// add this line for output
printf("%04s", $randomNumber);
The first argument in the printf() function "%04s" is the formatting string. The modulus character '%' indicates the start of the format. The '0' indicates that we want the extra space padded with the number '0'. The '4' indicates that we want the length to always be at least 4 digits. And the 's' indicates that we want to print the variable (from the second argument) as a string.
The printf() function doesn't actually alter the $randomNumber. So if you need to store a 'zero-padded' 4-digit number (or do other things with this number which require it to be 'zero-padded'), you could change the function to create a number one digit at a time and join them with the concatenation operator (the period), which will treat the $randomNumber as a string and thus not truncate the leading zeros: (this is how batman's function is set up)
mt_srand((double)microtime()*1000000);
$randomNumber = '';
$i = 0;
while ($i < 4)
{$randomNumber .= mt_rand(0,9);
$i++;}
echo $randomNumber;
Give that a shot.