Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increment non-existent variable in php loop

I have a foreach loop, inside of which I am building a big multi-dimensional array and doing lots of incriminating, like this:

$totalCosts['sawn']['materials'] += $sawnMaterialsCost;

On the first iteration of the loop, the key 'materials' is not set, so it throws an undefined index notice (not terrible, but annoying).

I can fix that by defining it before the loop like this:

$totalCosts['sawn']['materials'] = '0.00';

BUT, I have many keys I am filling by incrementing, and I don't like having to set each variable/key to '0' for every one before looping. Is there a better way to do this so the first iteration of the loop checks for a value and sets it to 1 if not found?

like image 618
Eckstein Avatar asked May 20 '18 15:05

Eckstein


People also ask

How to increment variable value in PHP?

C style increment and decrement operators represented by ++ and -- respectively are defined in PHP also. As the name suggests, ++ the increment operator increments value of operand variable by 1. The Decrement operator -- decrements the value by 1. Both are unary operators as they need only one operand.

What does => mean in PHP?

=> is the separator for associative arrays. In the context of that foreach loop, it assigns the key of the array to $user and the value to $pass .

How to increment string in PHP?

PHP has a built-in way of incrementing either a number or a string simply by placing ++ at the end of the variable. // Number $i = 1; $i++; // echo 2 echo $i; But you can also do this for letters; PHP will increment the variable to the next letter in the alphabet.

What is increment operator in PHP?

The PHP increment operators are used to increment a variable's value. The PHP decrement operators are used to decrement a variable's value.


1 Answers

$totalCosts['sawn']['materials'] = ($totalCosts['sawn']['materials'] ?? 0) + $sawnMaterialsCost;

??, an operator introduced in PHP 7, uses the left-hand operand if defined and not null, otherwise the right-hand operand.

The performance cost of ?? is negligible, unless you are doing millions of comparisons. On an Amazon c3.medium, I measured each at ~250ns more than a static assignment. On a loop of 10,000,000 that's a half-second penalty.

perf.code.

like image 60
bishop Avatar answered Oct 27 '22 15:10

bishop