Sum in array and "undefined index"

I want to summarize in my array:

<?php
if(isset($values[$key])) {
    $values[$key] += $total;
} else {
    $values[$key] = $total;
}

If I just write "+ =", I have a " Undefined index " error . Do you know an easier way? Because it is too long for a long code. Thanks

+4
source share
7 answers

You can cut it a little

<?php
if(!isset($values[$key]))
  $values[$key]= 0;
$values[$key] += $total;

but the way you wrote the code is already pretty concise and, more important, a pretty 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 triggered in the first place, it cannot be read.

PHP , 0 " " - , , .

+3

, array_sum ($ arrayname).

, -

array_sum(array_keys($array_name));
+1

:

$values[$key] = array_key_exists($key, $values) ? $values[$key] + $total : $total;

:

+1

$total

<?php 

$total = 0;

if(isset($values[$key])) {
   $total += $values[$key]; //Also equal to $total = $total + $values[$key];
} else {
    $total = $values[$key];
}
+1

:

<?php
$values[$key] = @$values[$key] + $total;
0

:

<?php
$values[$key] = isset($values[$key]) ? ($values[$key] + $total) : $total;
0

, , , . undefined index, $key, .

, , ? , , . , , .

, , , , , .

if (!isset($array[$key])) {
    $array[$key] = $total;
} else {
    $array[$key] += $total;
}

, , , , script, , .

0

Source: https://habr.com/ru/post/1627929/


All Articles