Numeric Literal Separator
Long sequences of digits are sometimes hard to read. Not for the
computer and PHP’s compiler, mind you, but for developers. The
optional numeric literal separator _
was added to make
code that uses large numbers, for instance, easier to read. The
_
character can be used to visually separate groups of
digits like so:
var_dump(1_000_000_000);
var_dump(1000000000);
Executing the code shown above will print the output shown below:
int(1000000000)
int(1000000000)
As you can see, 1_000_000_000
is equivalent to
1000000000
.
The numeric literal separator _
does not only work
with integers as shown in the example above but also with floating
point numbers as well as hexadecimal, binary, and octal values.
The _
character must be directly between two digits.
If it is used in an illegal place then a syntax error is
triggered:
var_dump(100_);
Executing the code shown above will print the error shown below:
PHP Parse error: syntax error, unexpected '_' (T_STRING),
expecting ')' in ...
Prefixing a sequence of digits with _
is a special
case as _100
, for instance, is a valid constant
name:
var_dump(_100);
Executing the code shown above will print the output shown below:
PHP Warning: Use of undefined constant _100 - assumed '_100'
(this will throw an Error in a future version of PHP) in ...
string(4) "_100"