Tutorial :PHP Array logic re-factor



Question:

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];      }  }  


Solution:1

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.


Solution:2

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];  


Solution:3

range is pretty useful in these scenarios

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

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »