PHP Operators and Control Structures
Operators let PHP expressions calculate values, compare data, and combine conditions. Control structures use those expressions to decide which code runs and how often it runs.
Common Operators
Arithmetic operators include +, -, , /, %, and *. Assignment operators such as = and += store or update values. Comparison operators include ===, !==, ==, !=, <, and >. Prefer strict comparisons (=== and !==) when you want to compare both value and type.
Logical operators such as &&, ||, and ! combine boolean expressions.
$quantity = 3;
$price = 12.50;
$total = $quantity * $price;
if ($total > 30 && $quantity >= 2) {
echo "Bulk order";
}
Conditional Statements
Use if, elseif, and else when different conditions require different actions.
$score = 82;
if ($score >= 90) {
$grade = "A";
} elseif ($score >= 80) {
$grade = "B";
} else {
$grade = "C or below";
}
For a value compared against several known alternatives, switch or match may be clearer. The match expression uses strict comparison and returns a value.
Loops
A for loop is useful when the number of iterations is known. while repeats while a condition remains true. foreach is usually the clearest choice for iterating over arrays.
$names = ["Ava", "Noah", "Mia"];
foreach ($names as $name) {
echo $name . PHP_EOL;
}
Use break to leave a loop and continue to skip to its next iteration. Avoid unnecessarily complex nested conditions; extracting logic into a named function often improves readability.
Practical Guidelines
Use strict comparisons for predictable results, group related conditions with parentheses when it improves clarity, and avoid relying on loose type conversion for user input. Validate and convert external values before using them in calculations or decisions.
Conclusion
Operators and control structures form the foundation of PHP logic. Once you understand how expressions, conditions, and loops work together, you can write code that is easier to test and maintain.