Computation at the top, simple output at the bottom

Summary

Put code for complex calculations in the top part of your program. That code puts values in variables. The bottom bit makes HTML using those variables.

Situation

You're writing a page that's complicated enough so that you can't keep it in your head all at once.

Action

PHP pages are usually in two parts:

  • <?php
  • // Some code that runs before any HTML has been produced.
  • ...
  • ?><!DOCTYPE html>
  • <html lang="en">
  •   ...
  •   <body>
  •     ...
  •     <?php
  •     // Code that runs while HTML is being processed.
  •     ...
  •   <body>
  • </html>

It's common to make a page as two chunks.

Two chunks

Put code for complex calculations in the top bit. That code puts values in variables. The bottom bit makes HTML using those variables.

This approach separates computation for business rules (top), from code for viewing the results (bottom).

Explanation

Divide up the page to reduce its complexity. When you're working on the top bit, don't worry about display deets. Leave that for later on.