Can this PHP statement with a isset() check be simplified?

  • A+
Category:Languages

Needing to check whether the item exists in the array and either add to it or increase the value by the amount.

if(isset($this->_costRemovedByLineItem[$objectId])) {     $this->_costRemovedByLineItem[$objectId] += $amount; }else{     $this->_costRemovedByLineItem[$objectId] = $amount; } 

I have a feeling this can be simplified.

 


Something that will work in all versions of PHP:

@$this->_costRemovedByLineItem[$objectId] += $amount; 

The @ (error control operator) will cause PHP to ignore the error caused by the non-existent index, create the element (with an empty value) and then add $amount to it, resulting in a value of $amount (as the empty value gets converted to 0 as a number).

Warning use of the @ operator could potentially make it harder to debug your code, as it will hide error messages that you may have needed to see (for example, even if $this doesn't exist, or there is no object element called _costRemovedByLineItem, PHP will create them along with the array). See the third case in my example code.

Alternatively in PHP7 you can use the Null Coalescing Operator:

$this->_costRemovedByLineItem[$objectId] = ($this->_costRemovedByLineItem[$objectId] ?? 0) + $amount; 

And in PHP < 7 you can use the ternary operator

$this->_costRemovedByLineItem[$objectId] = (isset($this->_costRemovedByLineItem[$objectId]) ? $this->_costRemovedByLineItem[$objectId] : 0) + $amount; 

A shorter example of each:

$amount = 4; @$a[5] += $amount; print_r($a); $b[6] = ($b[6] ?? 0) + $amount; print_r($b); @$c->x[5] += $amount; print_r($c); $d[3] = (isset($d[3]) ? $d[3] : 0) + $amount; print_r($d); 

Output:

Array ( [5] => 4 )  Array ( [6] => 4 ) stdClass Object (     [x] => Array ( [5] => 4 )  ) Array ( [3] => 4 ) 

Demo on 3v4l.org

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: