Conditional Logic (if)
In PHP,
if statements work just like in other C-style languages.php
The match Expression (PHP 8+)
Wait! PHP 8 introduced the
match expression. It's like a cleaner, safer version of switch that returns a value and doesn't require break statements.php
Loops in PHP
PHP provides several ways to repeat code:
foreach: The most common way to iterate through an Array.for: Best for a fixed number of iterations.while: Runs as long as a condition is true.
php
Wait! You can also get the key in a
foreach loop:php
Alternative Syntax
PHP has an alternative syntax for control flow that is widely used in HTML templates (like WordPress). It uses
: and endif; instead of {}.php
Summary
| Keyword | Description |
|---|---|
| if / elseif | Basic branching |
| switch | Traditional multi-way branch |
| match | Modern, safer branch (Expression) |
| foreach | Primary loop for arrays |
| continue | Skip to next iteration |
| break | Exit loop completely |
| Logic | Essential for building interactive websites |
| Safety | match is exhaustive and uses strict comparison |
| Modern | PHP 8 match is significantly cleaner than switch |
| Standard | Use foreach for almost everything in PHP |
| Template | Alternative syntax is great for embedding in HTML |