PHPglue PHPglue - 1 year ago 36
PHP Question

Is there a way to know if a number starts with 0 before PHP does an automatic octdec() conversion on it?

Consider the following in PHP:

$num = 011;
echo $num; // 9

I can get
as a base 10 number like:


So, you can tell PHP makes the conversion to a base 10 automatically.
What if i want to prevent unwanted octal numbers, which will convert to decimals automatically? What if both 9 and 11 were cast to (string)s and regex matched to be valid numbers?

If I had employees working on code on the back end using numbers with my API, this could be a real issue. Is there a way to test for that number with the
in front of it before, it's converted? Please help.

Answer Source

When PHP's source-code parser encounters a string such as 011 within PHP source-code, it will interpret the resulting value as an Octal constant, as illustrated by the following one-liner:

php -r '$foo=011; print (int)$foo; print "\n";'

But, if the same value is presented as "a literal string," it will be interpreted (by the runtime library, not by the parser), as a base-10 number:

php -r '$foo="011"; print (int)$foo; print "\n";'

Any value that is presented "to your API" ought to arrive "as a string," as in the second case, and therefore to consistently be interpreted as a base-10 number, whether-or-not it contains a leading zero. (Whew!! "Goody for you!")