Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

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.

like image 332
lukemh Avatar asked Jan 30 '19 02:01

lukemh


2 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;
like image 189
Devon Avatar answered Oct 12 '22 21:10

Devon


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

like image 27
Nick Avatar answered Oct 12 '22 19:10

Nick