Skip to content

Instantly share code, notes, and snippets.

@ewingd
Last active December 21, 2015 21:08
Show Gist options
  • Save ewingd/6365955 to your computer and use it in GitHub Desktop.
Save ewingd/6365955 to your computer and use it in GitHub Desktop.
facepalm for loop
<?php
// Before (this was repeated 3 times in one script, copy and pasted exactly...)
for($i=0,$btotal=0,$total=0,$page=1;$lclass=$row['class'],$lwhse=$row['whse'],$row=mysql_fetch_array($res);$i++,$total+=$row['cost'],$btotal+=$row['cost'],$gtotal+=$row['cost']) {
// ...snip.. 35 lines of echo statements dumping HTML
}
// Removing all the unused variables reduced it down to:
for ($i = 0; $row = mysql_fetch_array($res); $i++) {
// Same 35 lines of echo statements dumping HTML
}
// with $i only being used to count the number of records being returned.
// After further refactoring:
$data = $result->fetchAll(PDO::FETCH_ASSOC);
// Then pass $data off to a template and $i is no longer needed
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment