PHP Array Logical Reactor

PHP array logic refactor

I am trying to override the code ... This is PHP ...

I have the following:

$totals[] = "Total";
$totals[] = $counts['hole'][1] + $counts['warn'][1] + $counts['info'][1] + $counts['crit'][1];
$totals[] = $counts['hole'][2] + $counts['warn'][2] + $counts['info'][2] + $counts['crit'][2];
$totals[] = $counts['hole'][3] + $counts['warn'][3] + $counts['info'][3] + $counts['crit'][3];
$totals[] = $counts['hole'][4] + $counts['warn'][4] + $counts['info'][4] + $counts['crit'][4];
$totals[] = $counts['hole'][5] + $counts['warn'][5] + $counts['info'][5] + $counts['crit'][5];
$totals[] = $counts['hole'][6] + $counts['warn'][6] + $counts['info'][6] + $counts['crit'][6];

Why is this not working?

for($i; $i < 6; $i++ ){
    foreach( $severity as $sev ){
        $totals[$i] = $totals[$i] + $counts[$sev][$i];
    }
}
+3
source share
3 answers

You have an error in the for loop:

for ($i = 1; $i <= 6; $i++) {
    foreach ($severity as $sev) {
        $totals[$i] += $counts[$sev][$i];
    }
}

You forgot to initialize the variable $i.

+1
source

Indexes work from 1 to 6 (inclusive), so the loop forshould be like

for($i = 1; $i <= 6; $i++ ){
   ....

By the way, you can use

$totals[$i] += $counts[$sev][$i];
+1
source

range very useful in these scenarios

foreach( range(1,6) as $i ){
    foreach( $severity as $sev ){
        $totals[$i] += $counts[$sev][$i];
    }
}
0
source

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


All Articles