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?
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.
The str_pad() function pads a string to a new length.
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.
Now array[0] and array[1] is the first two digits. array[array. length-1] and array[array. length] are the last two.
$foo = sprintf('%04d', $foo + 1);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With