Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
471 views
in Technique[技术] by (71.8m points)

php - Understanding str_pad() with leading zeros

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...