views:

1363

answers:

3

If I have a variable in PHP containing 0001 and I add 1 to it, the result is 2 instead of 0002. How do I solve this problem?

+10  A: 
$foo = sprintf('%04d', $foo + 1);
chaos
Thanks, worked perfectly.
Ryan
+5  A: 

Another option is the str_pad() function.

$text = str_pad($text, 4, '0', STR_PAD_LEFT);
ceejayoz
+9  A: 

It would probably help you to understand the PHP data types and how they're affected when you do operations to variables of various types. You say you have "a variable in PHP say 0001", but what type is that variable? Probably a string, "0001", since an integer can't have that value (it's just 1). So when you do this:

echo ("0001" + 1);

...the + operator says, "Hm, that's a string and an integer. I don't know how to add a string and an int. But I DO know how to convert a string INTO an int, and then add two ints together, so let me do that," and then it converts "0001" to 1. Why? Because the PHP rules for converting a string to an integer say that any number of leading zeroes in the string are discarded. Which means that the string "0001" becomes 1.

Then the + says, "Hey, I know how to add 1 and 1. It's 2!" and the output of that statement is 2.

dirtside