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
0xprefix: e.g.0x11= 17 - Binary with
0bprefix: e.g.0b11= 3 - Octal with
0prefix: e.g.011= 9
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 explicit0onotation and have been recommending the0o.
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/0O prefixed numeric literals as well:
echo 0o7716_1412; // 16573194
0 Prefix Is Not Changed
The existing 0 prefix is not deprecated, and continue function exactly the same.
The 0o/0O prefixes are supported in addition to the existing 0 prefix.
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 true for is_numeric function either.
echo "016"; // "016"
is_numeric("0o77"); // false
is_numeric("0b11"); // false
is_numeric("0x16"); // false
Note that "016" returns true for is_numeric, and it is not changed:
is_numeric("016"); // true
Backwards Compatibility Impact
The 0o and 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 ...