Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force PHP to output a number preceded by zeros?

Tags:

php

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
like image 202
Andrew Avatar asked Feb 18 '10 18:02

Andrew


People also ask

How can I pad a value with leading zeros?

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.

How can I get the last two digits of a number in PHP?

Now array[0] and array[1] is the first two digits. array[array. length-1] and array[array. length] are the last two.


1 Answers

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 :

  • padding specifier = 0
  • width specifier = 2
  • integer = 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
like image 195
Pascal MARTIN Avatar answered Nov 03 '22 08:11

Pascal MARTIN