views:

65

answers:

3

Hi Guys,

How come when I set 00 as a value like this:

$var = 00;

it ouputs as 0 when I use it? How can I set 00 so that $var++ would become 01?

+6  A: 

Numbers in PHP (and virtually all languages) are not stored internally with leading (or in the case of decimal values, trailing) zeros.

There are many ways to display your numeric variables with leading zeros In PHP. The simplest way is to convert your value to a string, and pad the string with zero's until it's the correct length. PHP has a function called str_pad to do this for you:

$var = 0;
$var += 1;

// outputs '01'
echo str_pad($var, 2, '0', STR_PAD_LEFT);

Alternatively, the sprintf family of functions have a specifier for printing zero-padded values:

$var = 1;

// outputs '01'
printf("%02d", $var);
meagar
Note that it doesn't matter for 00, but for 01, etc. php will try to save the number as octal.
Adriano Varoli Piazza
+3  A: 

Using a function like printf or sprintf will do this much more easily for you.

$number = 1;
printf("%02d", $number); // Outputs 01

$number = 25;
printf("%02d", $number); // Outputs 25

You can set the minimum width by replacing the two with another number.

Tim Cooper
So: `$number = 25;printf("%04d", $number); // Outputs 0025?`
Liam Bailey
@Liam That's correct
Tim Cooper
+1  A: 

Also number_format() is your friend in formatting numbers.

http://php.net/manual/en/function.number-format.php

Great for ensuring there are 2 decimals for example.

Zurtri