Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Array logic re-factor

PHP Array logic re-factor

I'm trying to re-factor my 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 doesn't this work?

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

2 Answers

You have a bug in the for loop:

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

You forgot to initialize the $i variable.

like image 183
Alix Axel Avatar answered Jul 06 '26 15:07

Alix Axel


The indices run from 1 to 6 (inclusive), so the for loop should be like

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

BTW, you could use

$totals[$i] += $counts[$sev][$i];
like image 40
kennytm Avatar answered Jul 06 '26 15:07

kennytm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!