Control Structures in PHP

๐Ÿ“˜ PHP ๐Ÿ‘ 31 views ๐Ÿ“… Dec 22, 2025
โฑ Estimated reading time: 2 min

Control structures in PHP determine the flow of program execution. They allow your code to make decisions, repeat actions, and control how and when certain blocks of code run.


1. Conditional Statements

if Statement

Executes code if a condition is true.

$age = 20; if ($age >= 18) { echo "Adult"; }

ifโ€ฆelse Statement

Executes one block if true, another if false.

if ($age >= 18) { echo "Adult"; } else { echo "Minor"; }

ifโ€ฆelseifโ€ฆelse Statement

Used for multiple conditions.

$marks = 75; if ($marks >= 90) { echo "A"; } elseif ($marks >= 60) { echo "B"; } else { echo "C"; }

switch Statement

Used when comparing the same variable against multiple values.

$day = "Monday"; switch ($day) { case "Monday": echo "Start of week"; break; case "Friday": echo "Weekend coming"; break; default: echo "Regular day"; }

2. Looping Structures

for Loop

Used when the number of iterations is known.

for ($i = 1; $i <= 5; $i++) { echo $i; }

while Loop

Executes as long as the condition is true.

$i = 1; while ($i <= 5) { echo $i; $i++; }

doโ€ฆwhile Loop

Executes at least once before checking condition.

$i = 1; do { echo $i; $i++; } while ($i <= 5);

foreach Loop

Used to iterate through arrays.

$colors = ["Red", "Green", "Blue"]; foreach ($colors as $color) { echo $color; }

3. Loop Control Statements

break

Stops loop execution.

foreach ($colors as $color) { if ($color == "Green") { break; } }

continue

Skips current iteration.

for ($i = 1; $i <= 5; $i++) { if ($i == 3) { continue; } echo $i; }

4. Conditional Control Operators

Ternary Operator

Short form of ifโ€ฆelse.

$status = ($age >= 18) ? "Adult" : "Minor";

Null Coalescing Operator

Provides a default value if variable is null.

$username = $_GET['name'] ?? "Guest";

5. Match [removed]PHP 8+)

An improved alternative to switch.

$result = match ($status) { 'active' => 'User is active', 'inactive' => 'User is inactive', default => 'Unknown status', };

Conclusion

Control structures in PHP allow you to create dynamic and logical programs by making decisions and repeating actions. Mastering these structures is essential for writing efficient PHP code and for understanding frameworks like Laravel that rely heavily on conditional logic and loops.


๐Ÿ”’ Some advanced sections are available for Registered Members
Register Now

Share this Post


โ† Back to Tutorials

Popular Competitive Exam Quizzes