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

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

Posted by: admin July 12, 2020 Leave a comment


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;
    $this->_costRemovedByLineItem[$objectId] = $amount;

I have a feeling this can be simplified.

How to&Answers:

This method reduces it a bit, as you don’t need the else statement or to assign amount twice.

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


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;
$b[6] = ($b[6] ?? 0) + $amount;
@$c->x[5] += $amount;
$d[3] = (isset($d[3]) ? $d[3] : 0) + $amount;


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

Demo on 3v4l.org