for ($number = 1; $number <= 16; $number++) {
echo $number . "\n";
}
This code outputs:
1
2
3
...
16
How can I get PHP to output the numbers preceded by zeros?
01
02
03
...
16
To pad an integer with leading zeros to a specific length To display the integer as a decimal value, call its ToString(String) method, and pass the string "Dn" as the value of the format parameter, where n represents the minimum length of the string.
Now array[0] and array[1] is the first two digits. array[array. length-1] and array[array. length] are the last two.
You could use sprintf
to format your number to a string, or printf
to format it and display the string immediatly.
You'd have to specify a format such as this one, I'd say : %02d
:
0
2
d
(Even if you have what you want here, you should read the manual page of sprintf
: there are a lot of possibilities, depending on the kind of data you are using, and the kind of output formating you want)
And, as a demo, if temp.php
contains this portion of code :
<?php
for ($number = 1; $number <= 16; $number++) {
printf("%02d\n", $number);
}
Calling it will give you :
C:\dev\tests\temp>php temp.php
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With