PHP 7.4: Underscore numeric separator

TypeNew Feature

A simple, yet well thought-out change in PHP 7.4 is the numeric literal separator.

We are used to read numbers when they are grouped. For example, 1,000,000 is easier to subitize than 1000000. With numeric literal separator support in PHP, you can now use numbers in PHP like this:

$num = 1_000_000;

Prior to PHP 7.4, trying above would result in a syntax error:

Parse error: syntax error, unexpected '_000_000' (T_STRING) in ... on line ...

PHP engine removes the underscores when lexing.

Support for all numeric notations

You can use the underscore pattern in all PHP numeric notations.

  • Decimal: 1_000_000
  • Scientific: 6.62_607_004e-34
  • Float: 0.300_000_000_000_000_04
  • Binary: 0b1111_0000_1001_1111_1001_0010_1010_1001
  • Octal: 0123_7264
  • Hex: 0xBEEF_BABE

Disallowed patterns

The RFC also mentions the patterns that are not allowed:

  • Two or more underscores: 1__6
  • Underscores before and after the number: _16 and 16_
  • Underscore around the decimal point: 1_.6 or 1._6
  • Underscore around the e in scientific notation: 1.6_e-28 or 1.6e_-28
  • Underscore around the b in binary notation: 0_b01010 or 0b_010101
  • Underscore around the x in hex notation: 0_xf00d or 0x_food

Backwards compatibility

Because the underscore separator would have thrown a syntax error in versions prior 7.4, all existing code should work without any problems. It is not possible to polyfill this behavior, so if you plan to use this feature, keep in mind that you will need to bump your minimum PHP version to 7.4.

RFC discussion Implementation