Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse error: Invalid numeric literal

I have the following error while running this code below:

Code:

<?php
    $a = array(00001, 00008, 00009, 00012);
    print_r($a);
?>

Error:

Parse error: Invalid numeric literal.

Why this issue occurred and how do i solve this?

like image 574
Rana Ghosh Avatar asked Nov 22 '16 07:11

Rana Ghosh


2 Answers

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
  • Example of PHP7 vs PHP5: https://3v4l.org/GRZF2
  • http://php.net/manual/en/language.types.integer.php
  • Manual: http://php.net/manual/en/migration70.incompatible.php
like image 103
Qirel Avatar answered Oct 23 '22 19:10

Qirel


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.

like image 27
ChristianF Avatar answered Oct 23 '22 18:10

ChristianF