Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 589
Ryan Avatar asked Apr 05 '09 02:04

Ryan


People also ask

How can I add zero in front of a number in PHP?

Using sprintf() Function: The sprintf() function is used to return a formatted string. Syntax: sprintf(format, $variable) // Returns the variable formatted according to the format provided. Example 1: This example uses sprintf() function to display the number with leading zeros.

Which of the following function pads one string with another in PHP?

The str_pad() function pads a string to a new length.

What is Str_pad function in PHP?

The str_pad() function is a built-in function in PHP and is used to pad a string to a given length. We can pad the input string by any other string up to a specified length. If we do not pass the other string to the str_pad() function then the input string will be padded by spaces.

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

$foo = sprintf('%04d', $foo + 1);
like image 114
chaos Avatar answered Sep 25 '22 14:09

chaos