I want to sum in my array :
<?php
if(isset($values[$key])) {
$values[$key] += $total;
} else {
$values[$key] = $total;
}
If I just write "+=", I have error "Undefined index". Do you know an easier way? Because is too long on a long code. Thanks
You can shorten it a bit
<?php
if(!isset($values[$key]))
$values[$key]= 0;
$values[$key] += $total;
but the way you wrote the code already is a quite succinct and, more importantly, quite clean way.
edit: the error occurs in the first place because when writing
$values[$key] += $total;
, internally it is the same as $values[$key] = $values[$key] + $total
- and when $value[$key] is not initiated in the first place, it can not be read.
PHP normally assumes that it is 0 then and throws the "key not defined"-note to notificate the programmer that he forgot to initiate an element of the array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With