PHP 8.1: Explicit Octal numeral notation
PHP supports various numeral systems, including the default decimal (base-10), binary (base-2), octal (base-8), and hex (base-16).
Numeral systems apart from decimal are prefixed with their own prefix:
- Hex with
- Binary with
- Octal with
In PHP 8.1 and later, Octal numerals also support the
0o (zero, followed by o as in Oscar) prefix, which means octal numeric literals can be made more obvious and readable that they are indeed octal numerals.
0O (zero, followed by upper case O as in Oscar) is also supported.
Many programming languages use
0prefix for octal numeric literals, just like PHP. However, many languages also support the explicit
0onotation and have been recommending the
echo 0xff; // 255 echo 0b111; // 7 echo 77; // 77 echo 077; // 63 echo 0o77; // 63, In PHP 8.1 echo 0O77; // 63, In PHP 8.1
077 === 63; // true 077 === 0o77; // true 077 === 0O77; // true
Further, the underscore numeric separators are supported in
0O prefixed numeric literals as well:
echo 0o7716_1412; // 16573194
0 Prefix Is Not Changed
0 prefix is not deprecated, and continue function exactly the same.
0O prefixes are supported in addition to the existing
No Changes in Numeric Strings
Numeric strings, i.e. strings that contain a number, are not impacted by this change.
"0o16" (as a string) will not be interpreted as a number, and does not return
is_numeric function either.
echo "016"; // "016" is_numeric("0o77"); // false is_numeric("0b11"); // false is_numeric("0x16"); // false
is_numeric, and it is not changed:
is_numeric("016"); // true
Backwards Compatibility Impact
0O prefixes are new prefixes, that were not supported in older PHP versions. Attempting to use them in older PHP versions result in a syntax error:
$value = 0o77;
Parse error: syntax error, unexpected identifier "o77" in ... on line ...