The "Null Coalescing Assignment Operator" (or null coalesce assignment
operator) was proposed and accepted in
https://wiki.php.net/rfc/null_coalesce_equal_operator

I propose even more such operators:
null coalesce addition assignment ??+= (for strings and numbers)
null coalesce subtraction assignment ??-=
null coalesce increment ??++
null coalesce decrement ??--
null coalesce multiplication assingment ??*=


## Details

Each block contains 3 equivalent statements.

$x ??+= 5;  // proposed new syntax
($x ??= 0) += 5;  // syntax with null coalesce assignment operator
$x = ($x ?? 0) + 5;  // syntax with simple null coalesce operator

$x ??+= 'suffix';  // proposed new syntax
($x ??= '') += 'suffix';  // syntax with null coalesce assignment operator
$x = ($x ?? '') + 'suffix';  // syntax with simple null coalesce operator

$x ??++;  // proposed new syntax
($x ??= 0)++;
$x = ($x ?? 0) + 1;

$x ??*= 2;  // proposed new syntax
($x ??= 1) *= 2;
$x = ($x ?? 1) * 2;

Note that in each case PHP needs to determine the "neutral element" of
the operation.
For string concat this is the empty string. For number addition this
is 0. For number multiplication it is 1.


## Example:

For me, the most common use case would be something like this:

$fruitpacks = [
  ['apples', 3],
  ['pears', 1],
  ['apples', 6],
  ['grapes', 22],
];

$totals_by_name = [];
foreach ($fruitpacks as [$name, $amount]) {
  $totals_by_name[$name] ??+= $amount;  // proposed new syntax
}

$totals_by_name_expected = [
  'apples' => 9,
  'pears' => 1,
  'grapes' => 22,
];

assert($totals_by_name === $totals_by_name_expected);


## Notes

In PHP, the "+=" operator already behaves almost like "??+=", but adds
a "Notice: Undefined offset" or "Notice: Undefined variable", if the
left side is not defined yet.
hhvm apparently does not produce this notice.
https://3v4l.org/l0l0K

-- 
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to