Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum in array and "undefined index"

Tags:

php

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

like image 901
Gaylord.P Avatar asked Mar 14 '23 08:03

Gaylord.P


1 Answers

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.

like image 118
Franz Gleichmann Avatar answered Mar 19 '23 23:03

Franz Gleichmann