views:

40

answers:

3

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];
    }
}
+1  A: 

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.

Alix Axel
Yes, I did forget to initialize the $i var... This caused undesired results because all of this was inside another foreach loop. I also adjusted the code to reflect the += ... I have not used php in a while and wasn't sure if that sytax was allowed. (I'm a python hacker normally). Thanks!
foxhop
+1  A: 

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];
KennyTM
Thank you for the answer. you were spot on correct and your input was helpful, however I read 'Alix Axel' answer first.
foxhop
A: 

range is pretty useful in these scenarios

foreach( range(1,6) as $i ){
    foreach( $severity as $sev ){
        $totals[$i] += $counts[$sev][$i];
    }
}
macek
`foreach` is faster and prettier but `range` uses more memory, specially on large ranges.
Alix Axel
@Alix, `range(1,6)` is not large. No need to optimize it past that.
macek