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

跟風遠走 提交于 2019-11-30 09:04:53
$foo = sprintf('%04d', $foo + 1);
dirtside

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.

ceejayoz

Another option is the str_pad() function.

$text = str_pad($text, 4, '0', STR_PAD_LEFT);
MRidul Chatterjee
<?php
#how many chars will be in the string
$fill = 6;
#the number
$number = 56;
#with str_pad function the zeros will be added
echo str_pad($number, $fill, '0', STR_PAD_LEFT);
// The result: 000056
?>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!