In PHP, how do I add to a zero-padded numeric string and preserve the zero padding?

Ryan picture Ryan · Apr 5, 2009 · Viewed 14.8k times · Source

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?

Answer

chaos picture chaos · Apr 5, 2009
$foo = sprintf('%04d', $foo + 1);