Home > Software engineering >  Prevent interpreting leading zero for number as octal
Prevent interpreting leading zero for number as octal

Time:11-14

JavaScript allows us to use use strict to prevent using octals with leading zero (throws an error, but better than using octal value without notifying)

How can we do the same with php? Can we set any global flag that will prevent PHP from interpreting leading zero as octal?

CodePudding user response:

Can we set any global flag that will prevent PHP from interpreting leading zero as octal?

No

How can we do the same with php?

Own wrapper/filter, something like:

function getDecimalNumber(string $num): int 
{
    $decimalNum = filter_var($num, FILTER_VALIDATE_INT);
    if ($decimalNum === false) {
        throw new \InvalidArgumentException("The '$num' is not a decimal number.");
    }

    return $decimalNum;
}

CodePudding user response:

There is no global setting that I know of. But you could strip leading zeroes.

$str = ltrim( $str, '0' );

CodePudding user response:

To use octal notation, precede the number with a 0 (zero)

Straight from the PHP documentation. From that you can deduce that any integer leading with 0 will be considered as octal.

Check out: PHP:Integers - Manual

  • Related