0

Is it possible for me to display the sum at the heading before the program runs through?

while (($data = fgetcsv($handle, 1000, ","))) {

if($data[2] != $prevRow2) {

 echo '</div>';
 if ($prevRow2 != '') {
  $stringData .= '</Payment>';
 }
 echo "<div id=\"row\">";
 echo $sum;
 $row++;
           $sum = 0;
}
 else { echo "<div id=\"filler\"></div>";}

 foreach ($data as $key => $d) {
  if ($key != 1) {
   echo "<div class=\"field\">" .$d . "</div>";
  }
 }

 $sum +=$data[6]; 
 echo "<br/>";
 echo "<div id=\"filler\"></div>"; 
                      $prevRow2 = $data[2];
} 

fclose($handle);
}

1 Answer 1

3

You could buffer the output, print out the heading with the sum after the loop ran through, and then output the buffer.

This could be accomplished simply by not echoing but assigning all the values to a variable and echoing that variable at the end - or by using the ob_start, ob_end_flush, etc functions.

So in your example, instead of:

while (true) {
  echo "lots of code";
  echo "some variable: " . $variable;
  $sum = $sum + 1;
}

Write:

while (true) {
  $output .= "lots of code";
  $output .= "some variable: " . $variable;
  $sum = $sum + 1;
}

echo $sum;
echo $output;
Sign up to request clarification or add additional context in comments.

2 Comments

I am not able to get it working. while (($data = fgetcsv($handle, 1000, ","))) { if($data[2] != $prevRow2) { echo '</div>'; if ($prevRow2 != '') { $stringData .= '</Payment>'; } echo $sum; echo "<div id=\"row\">"; $sum=0; $row++; } else { echo "<div id=\"filler\"></div>";} if ($data[2] == $prevRow2){ $sum += $data[6]; } else {$sum=$data[6];} foreach ($data as $key => $d) { if ($key != 1) { echo "<div class=\"field\">" .$d . "</div>"; } } echo "<br/>"; echo "<div id=\"filler\"></div>"; $prevRow2 = $data[2]; }
Could you edit your question by formatting the code? Kinda difficult reading it in the comment. What error do you get?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.