Parse error: Invalid numeric literal

Posted on

Parse error: Invalid numeric literal – Here in this article, we will share some of the most common and frequently asked about PHP problem in programming with detailed answers and code samples. There’s nothing quite so frustrating as being faced with PHP errors and being unable to figure out what is preventing your website from functioning as it should like php and arrays . If you have an existing PHP-based website or application that is experiencing performance issues, let’s get thinking about Parse error: Invalid numeric literal.

I have the following error while running this code below:


    $a = array(00001, 00008, 00009, 00012);


Parse error: Invalid numeric literal.

Why this issue occurred and how do i solve this?

Solution :

This comes from the changes made to how integers, specifically octals, are handled in PHP7 (as oppsoed to PHP5).

From the documentation (from PHP7 migration)

Invalid octal literals

Previously, octal literals that contained invalid numbers were silently truncated (0128 was taken as 012). Now, an invalid octal literal will cause a parse error.

From the documentation of integers

Prior to PHP 7, if an invalid digit was given in an octal integer (i.e. 8 or 9), the rest of the number was ignored. Since PHP 7, a parse error is emitted.

Either use them as strings, or actual integers

$a = array(1, 8, 9, 12); // Integers
$a = array("00001", "00008", "00009", "00012"); // Strings

This is because all numbers starting with 0 is considered octal values, which has an upper limit of 8 digits per position (0-7). As stated in the PHP manual, instead of silently dropping the invalid digits they now (7.x) produce the above warning.

Why are you writing your numbers like that though? If the leading zeroes are significant, then it’s not a number you have but a string. Should you need to do calculations on those as if they were numbers, then you need to add the leading zeroes when outputting the values to the client.
This can be done with printf() or sprintf() like this:

$number = 5;
printf ("%05$1d", $number);

Please see the manual for more examples.

Sometime an apparently valid numeric literal is being detected as an invalid numeric literal.

This is a regression since php5.4

You can be fix this by changing the array to:

$a =array(1,8,9,12);   

$a = array('0001','0008','0009','0012'); //alternative method for fix


decimal     : [1-9][0-9]*(_[0-9]+)*|0

octal       : 0[0-7]+(_[0-7]+)*

from document regex for consider value as decimal and octal are given above

In this scenario with value is 00008, 00009 not pass validation for octal or decimal as well. since it is given error, parse parameter to string is solving problem partially.

Note: In PHP any number starts from zero considered as octal but 8 and
9 will not used in octal number resulting throw this error.

Leave a Reply

Your email address will not be published. Required fields are marked *