了解以零开头的str_pad() [英] Understanding str_pad() with leading zeros

查看:101
本文介绍了了解以零开头的str_pad()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试构建php函数并发现了一些奇怪的行为,甚至无法提出一个适当的问题,因此,如果有人可以解释发生了什么,我将不胜感激.

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;

根据需要,这使我得到00123.

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;

这将返回00083.如果用户输入00123,也会发生同样的事情.

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.

推荐答案

0开头的整数文字被解释为以8为底.您的第二个$x值为83.请参阅整数手册了解详情.

Integer literals starting with 0 are interpreted base 8. Your second $x has the value 83. See the manual on integers for details.

intval()函数可让您在读取用户字符串时指定基数.

The intval() function lets you specify the base if you're reading a user string.

如果我们在谈论文字,那么在PHP中,文字0是十进制,而在

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.

这篇关于了解以零开头的str_pad()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆