了解带有前导零的 str_pad()
我正在尝试构建一个 php 函数,发现了一些奇怪的行为,我什至无法提出一个正确的问题,所以如果有人可以解释发生了什么,我将不胜感激。
我正在处理一组带有前导零的数字,维护它们很重要,但用户几乎从不输入前导零。所以我使用这个:
$x = 123;
$n = 5;
$x = str_pad((int)$x,$n,"0",STR_PAD_LEFT);
echo $x;
并且,根据需要,这会得到 00123。
当我测试用户在其数字之前输入零时,会发生奇怪的事情。
$x = 0123;
$n = 5;
$x = str_pad((int)$x,$n,"0",STR_PAD_LEFT);
echo $x;
这会返回 00083。如果用户输入 00123,也会发生同样的情况。
这个结果让我完全困惑了。预先感谢您对这里发生的事情的任何解释。
I'm trying to build a php function and discovered some weird behavior and I can't even formulate a proper question, so if anyone can explain what is going on, I would appreciate it.
I'm working with a set of numbers with leading zeros, and its important that they be maintained, but users almost never input leading zeros. So I use this:
$x = 123;
$n = 5;
$x = str_pad((int)$x,$n,"0",STR_PAD_LEFT);
echo $x;
and, as desired, this gets me 00123.
The weird stuff happens when I tested for a user inputting a zero before their number
$x = 0123;
$n = 5;
$x = str_pad((int)$x,$n,"0",STR_PAD_LEFT);
echo $x;
This returns 00083. Same thing happens if a user were to input 00123.
That result has me completely bewildered. Thanks in advance for any explanation of what's going on here.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
以
0
开头的整数文字被解释为 base 8。您的第二个$x
的值为 83。 请参阅有关详细信息,请参阅整数手册。如果您正在读取用户字符串,
intval()
函数可让您指定基数。如果我们谈论文字,在 PHP 中,文字
0
是十进制,而在 C 和 C++ 它是八进制的。正是这些微小的差异让生活变得有趣。Integer literals starting with
0
are interpreted base 8. Your second$x
has the value 83. See the manual on integers for details.The
intval()
function lets you specify the base if you're reading a user string.If we're talking about literals, in PHP the literal
0
is decimal, while in C and C++ it is octal. It's the little differences that make life fun.