php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #76313 RFE: shorthand for ternary assignment "?="
Submitted: 2018-05-08 16:48 UTC Modified: 2018-05-08 16:56 UTC
From: php at richardneill dot org Assigned:
Status: Suspended Package: Variables related
PHP Version: 7.2.5 OS: Linux
Private report: No CVE-ID: None
Have you experienced this issue?
Rate the importance of this bug to you:

 [2018-05-08 16:48 UTC] php at richardneill dot org
Description:
------------
In the same way that we can have:
  $x += $y;
as a shorthand for:
  $x = $x + $y;

it would be helpful if we could have:
  $x ?= $y;
as a shorthand for:
  $x = $x ?: $y;

Alternatively, we could have the following syntax, which are more aligned with the 2 ways the ternary operator works, though I think it might less useful:
  $x ?:= $y;          //c.f.   $x = $x ?: $y;
  $x ?=  $y : $z;     //c.f.   $x = $x ?  $y : $z;


This would be nice to have, simplify quite a lot of typing, and be consistent with all the other operators such as "*=" and ".=" . Thank  you for your consideration and your time.

A similar request exists here: Bug #72047 though as that bug has been closed, I assume (please correct me if I'm wrong) that it's better to open a new one. In that bug, the idea is for "null coalescing", whereas I think it's more useful to deal with anything "falsey", bearing in mind that many data sources originate as web forms.


Test script:
---------------
<?php
$name1 = "Jane";
$name2 = "";

$name1 ?= "[TBC]";
$name2 ?= "[TBC]";

echo "$name1 and $name2 are attending this event.";
//    Jane and [TBC] are attending this event."
?>


Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2018-05-08 16:56 UTC] requinix@php.net
-Status: Open +Status: Suspended
 [2018-05-08 16:56 UTC] requinix@php.net
See https://wiki.php.net/rfc/short_ternary_equal_operator for ?:=

But trying to cram the complete ternary form into a shorthand
  $x ?= $y : $z;
looks too confusing.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Tue Apr 23 23:01:29 2024 UTC