Introduced in PHP 7.4, an underscore (_
) can be used as a numeric separator to act as a visual separation between groups of digits. The purpose of having numeric separators is to improve readability of numeric literals. For example:
// PHP 7.4+ $million = 1_000_000; echo $million; // 1000000 var_dump($million === 1000000); // true
Numeric separators can be used with the following numeric literals:
- Decimal;
- Float;
- Scientific Notation;
- Binary;
- Octal;
- Hexadecimal.
Numeric separators have no semantic meaning, beyond improving readability of (long) numeric literals. In fact, numeric literals are parsed as if the underscores were absent:
// PHP 7.4+ // decimal echo 1_000_000; // 1000000 // float echo 1_000.123_456; // 1000.123456 // scientific echo 1.23_45e+6; // 1234500
// PHP 7.4+ // binary echo 0b10_11; // 11 echo 0B10_11; // 11 // octal echo 0_30_071; // 12345 echo 030_071; // 12345 echo 0o30_071; // 12345 (PHP 8.1+) echo 0O30_071; // 12345 (PHP 8.1+) // hexadecimal echo 0xddd_5; // 56789 echo 0Xddd_5; // 56789
When using an underscore (_
) between digits, the following are considered invalid:
- When there's more than one underscore between any two digits;
- When an underscore is not directly between two digits;
- When a numeric literal starts or ends with an underscore;
- When an underscore is used before or after a decimal point (or other "special positions" such as, exponent, number sign, etc.).
For example:
// PHP 7.4+
// Parse error: syntax error, unexpected identifier "__000"
100__000;
// PHP 7.4+ // Warning: Use of undefined constant _1234 - assumed '_1234' (this will throw an Error in a future version of PHP) _1234; +_1234; -_1234; // PHP 8+ // Fatal error: Uncaught Error: Undefined constant "_1234" _1234; +_1234; -_1234;
// PHP 7.4+
// Parse error: syntax error, unexpected identifier "_"
100_;
// PHP 7.4+
// Parse error: syntax error, unexpected identifier "_"
1_.23;
// PHP 7.4+ // Parse error: syntax error, unexpected identifier "e_23" 1e_23; // Parse error: syntax error, unexpected identifier "_e23" 1_e23; // Parse error: syntax error, unexpected identifier "e" 1e+_23; 1e-_23;
// PHP 7.4+ // Parse error: syntax error, unexpected identifier "..." 0b_10_11; 0B_10_11; 0o_30_071; 0O_30_071; 0x_ddd_5; 0X_ddd_5;
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.