5 votes

I don't understand why I get the error "Invalid numeric literal" in this PHP code

Something very strange happens to me in this code.

I happen to be writing a block switch in this way:

switch ($intIdElemento)
{
    case 01: 
        // ... código
        break;

    case 02: 
        // ... código
        break;

    case 03: 
        // ... código
        break;

    case 04: 
        // ... código
        break;

    case 05: 
        // ... código
        break;

    case 06: 
        // ... código
        break;

    case 07: 
        // ... código
        break;

    case 08:           //¡ERROR!
        // ... código
        break;

    default:
        break;

}

It allows me to evaluate numeric cases written with leading zero only up to the 07 . When I put from case 08: from now on, the color of the number changes in the editor and if I run the code it does not work, I get this error:

PHP Parse error: Invalid numeric literal in ...

The indicated line is that of any case written with a leading zero and whose value is greater than seven.

Why does it not support such values as from 08 ?

I am using the version 7.0.12 of PHP.

6voto

Einer Points 16588

The error is due to a change made in php 7.x so that 08 is not treated as an octal literal . According to the commentary of nikic@php.net (the last one on the page):

Numbers starting with 0 are octal literals. 08 is not a valid octal literal. valid octal literal, so you will get an error now. Previously it was treated silently as 0.

The recommendation they give is to specify them as string and it works perfect:

$intIdElemento = '08';
switch ($intIdElemento)
{
    case 01: 
        // ... código
        break;

    case 02: 
        // ... código
        break;

    case 03: 
        // ... código
        break;

    case 04: 
        // ... código
        break;

    case 05: 
        // ... código
        break;

    case 06: 
        // ... código
        break;

    case 07: 
        // ... código
        break;
     case '08': //¡PERFECTO!

        break;

    default:
        break;

}

4voto

Trauma Points 17600

Simple:

To use octal notation, the number is prefixed with a 0 (zero).

PHP recognizes several numerical bases :

  • Decimal (base 10): numbers ordinary people , that do not begin with 0 .

  • Hexadecimal (base 16): it is preceded by 0x to the number: 0xF => 15.

  • Octal (base 8): the number begins with an 0 .

The last point is responsible for your problem: the digits in octal base. cannot be greater than 7 .

This is the same error that would occur if you did not attempt to 0x14G8 -> Also is a valid number in hexadecimal base .

More information:

Wikipedia: Octal system.

Wikipedia: Hexadecimal system.

php.net: Integers.

HolaDevs.com

HolaDevs is an online community of programmers and software lovers.
You can check other people responses or create a new question if you don't find a solution

Powered by:

X