How to prevent PHP from doing octal math in conditionals? (why does 08 === 0)

537 views Asked by At

I was working with code that parses crontab.

https://stackoverflow.com/a/5727346/3774582

I found it works great, however I found that if I made a cron like

0 * * * *

It would run at the 0 minute, the 8th minute, and the 9th minute. I broke down every line of the code.

https://gist.github.com/goosehub/7deff7928be04ec99b4292be10b4b7b0

I found that I was getting this conditional for the value of 0 if the current minute was 8.

08 === 0

I tested this with PHP

if (08 === 0) {
    echo 'marco';
}

After running that, I saw marco on the output. It appears PHP is treating 08 as an octal. Because in octal after 07 is 010, 08 and 09 is evaluated as 00.

How can I force a decimal comparison in this conditional?

1

There are 1 answers

0
Goose On BEST ANSWER

From the PHP docs in Integer

http://php.net/manual/en/language.types.integer.php

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

However, don't just use ltrim($time[$k], '0') because this will turn 0 into . Instead, use a regular expression. In this case, /^0+(?=\d)/.

In this case, apply it to the $time[$k] input like so.

$time[$k] = preg_replace('/^0+(?=\d)/', '', $time[$k]);