How to Convert an Octal String to an Integer in PHP?

You can convert an octal string to an integer by using the octdec() function, for example, like so:

var_dump(octdec('30071')); // int(12345)
var_dump(octdec('030071')); // int(12345)
var_dump(octdec('0o30071')); // int(12345) (PHP 8.1+)
var_dump(octdec('0O30071')); // int(12345) (PHP 8.1+)

This works for values prefixed with 0, 0o and 0O, as well as values that don't have any of these prefixes.

For invalid values passed to octdec() (such as non-numeric values), this would show a deprecation message in PHP 7.4+ (and silently ignored in versions prior):

// ...

// Deprecated: Invalid characters passed for attempted conversion, these have been ignored
var_dump(octdec('foobar'));

To support conversion of octal strings with radix prefixes (i.e. 0o or 0O) in versions of PHP before v8.1, you could do something like the following:

// PHP <8.1
function octToDec(string $str): int {
    if (strpos(strtolower($str), '0o') === 0) {
        $str = substr($str, 2);
    }

    return octdec($str);
}

var_dump(octToDec('30071')); // int(12345)
var_dump(octToDec('030071')); // int(12345)
var_dump(octToDec('0o30071')); // int(12345)
var_dump(octToDec('0O30071')); // int(12345)

This works in the following way:

  1. Strip out 0o (or 0O) octal prefixes, if any;
  2. Call octdec() to convert the octal string to a decimal number and return the resulting integer.

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.