Control Flow, Functions, Includes, and Reusable PHP Code
Write real program logic with conditions, loops, functions, and file inclusion patterns that make PHP code maintainable.
Inside this chapter
- Conditional Logic
- Loops
- Functions
- include and require
- Practical Example
Series navigation
Study the chapters in order for the clearest path from PHP basics to backend architecture, security, deployment, and production engineering habits. Use the navigation at the bottom to move smoothly through the full tutorial series.
Conditional Logic
if ($score >= 80) {
echo "Excellent";
} elseif ($score >= 50) {
echo "Pass";
} else {
echo "Try again";
}
Conditionals are used in validation, permissions, business rules, pricing, routing, and branching output behavior.
Loops
foreach ($courses as $course) {
echo $course . "<br>";
}
Loops are essential for rendering lists, processing records, generating table rows, and iterating through request or database data.
Functions
function calculateTotal($price, $taxRate) {
return $price + ($price * $taxRate);
}
Functions reduce repetition and help organize code by responsibility. Beginners should build the habit of extracting meaningful reusable logic instead of repeating the same blocks.
include and require
require 'config.php';
include 'header.php';
These statements allow PHP files to reuse shared code, layouts, or configuration. require is generally used when the file is essential, while include is softer and may allow execution to continue in some cases.
Practical Example
A website may use one shared database connection file, one header include, one footer include, and multiple helper functions across many pages. Reusability is a major reason PHP projects can stay manageable.