PHP Beginner

PHP Control Structures (If, Else, Loops)

CodingerWeb
CodingerWeb
24 views 50 min read

PHP Control Structures

Control structures allow you to control the flow of your program execution. They determine which code blocks execute based on conditions or repetition needs.

If Statement

Execute code only if a condition is true:

<?php
$age = 18;

if ($age >= 18) {
    echo "You are an adult";
}

// Single line (no braces needed)
if ($age >= 18) echo "Adult";
?>

If-Else Statement

Execute different code blocks based on condition:

<?php
$temperature = 25;

if ($temperature > 30) {
    echo "It's hot outside";
} else {
    echo "It's not too hot";
}

// Ternary alternative
echo ($temperature > 30) ? "Hot" : "Not hot";
?>

If-ElseIf-Else Statement

Handle multiple conditions:

<?php
$score = 85;

if ($score >= 90) {
    $grade = "A";
} elseif ($score >= 80) {
    $grade = "B";
} elseif ($score >= 70) {
    $grade = "C";
} elseif ($score >= 60) {
    $grade = "D";
} else {
    $grade = "F";
}

echo "Your grade is: " . $grade;
?>

Switch Statement

Compare a variable against multiple values:

<?php
$day = "Monday";

switch ($day) {
    case "Monday":
        echo "Start of work week";
        break;
    case "Tuesday":
    case "Wednesday":
    case "Thursday":
        echo "Midweek";
        break;
    case "Friday":
        echo "TGIF!";
        break;
    case "Saturday":
    case "Sunday":
        echo "Weekend!";
        break;
    default:
        echo "Invalid day";
}
?>

Match Expression (PHP 8+)

Modern alternative to switch:

<?php
$status = 200;

$message = match($status) {
    200 => "OK",
    404 => "Not Found",
    500 => "Server Error",
    default => "Unknown Status"
};

echo $message;
?>

While Loop

Repeat code while condition is true:

<?php
$counter = 1;

while ($counter <= 5) {
    echo "Count: " . $counter . "
";
    $counter++;
}

// Practical example: reading file
$file = fopen("data.txt", "r");
while (!feof($file)) {
    $line = fgets($file);
    echo $line;
}
fclose($file);
?>

Do-While Loop

Execute code at least once, then repeat while condition is true:

<?php
$number = 10;

do {
    echo "Number: " . $number . "
";
    $number--;
} while ($number > 0);

// Useful for user input validation
do {
    $input = readline("Enter a number (1-10): ");
} while ($input < 1 || $input > 10);
?>

For Loop

Loop with initialization, condition, and increment:

<?php
// Basic for loop
for ($i = 1; $i <= 10; $i++) {
    echo "Iteration: " . $i . "
";
}

// Multiplication table
for ($i = 1; $i <= 10; $i++) {
    for ($j = 1; $j <= 10; $j++) {
        echo ($i * $j) . "	";
    }
    echo "
";
}

// Reverse loop
for ($i = 10; $i >= 1; $i--) {
    echo $i . " ";
}
?>

Foreach Loop

Iterate through arrays and objects:

<?php
// Indexed array
$fruits = ["apple", "banana", "orange"];

foreach ($fruits as $fruit) {
    echo "Fruit: " . $fruit . "
";
}

// With index
foreach ($fruits as $index => $fruit) {
    echo "$index: $fruit
";
}

// Associative array
$person = [
    "name" => "John",
    "age" => 30,
    "city" => "New York"
];

foreach ($person as $key => $value) {
    echo "$key: $value
";
}

// Modify array values
$numbers = [1, 2, 3, 4, 5];
foreach ($numbers as &$number) {
    $number *= 2; // Double each number
}
print_r($numbers); // [2, 4, 6, 8, 10]
?>

Break and Continue

Control loop execution:

<?php
// Break - exit loop completely
for ($i = 1; $i <= 10; $i++) {
    if ($i == 5) {
        break; // Exit loop when i equals 5
    }
    echo $i . " ";
} // Output: 1 2 3 4

echo "
";

// Continue - skip current iteration
for ($i = 1; $i <= 10; $i++) {
    if ($i % 2 == 0) {
        continue; // Skip even numbers
    }
    echo $i . " ";
} // Output: 1 3 5 7 9

// Break with levels (nested loops)
for ($i = 1; $i <= 3; $i++) {
    for ($j = 1; $j <= 3; $j++) {
        if ($i == 2 && $j == 2) {
            break 2; // Break out of both loops
        }
        echo "($i, $j) ";
    }
}
?>

Alternative Syntax

PHP provides alternative syntax for control structures:

<?php
$showContent = true;
?>

<!-- Alternative if syntax -->
<?php if ($showContent): ?>
    <div>Content is visible</div>
<?php else: ?>
    <div>Content is hidden</div>
<?php endif; ?>

<!-- Alternative foreach syntax -->
<ul>
<?php foreach ($fruits as $fruit): ?>
    <li><?= $fruit ?></li>
<?php endforeach; ?>
</ul>

Practical Examples

Number Guessing Game

<?php
$secretNumber = rand(1, 10);
$guess = 0;
$attempts = 0;

do {
    $guess = (int)readline("Guess a number (1-10): ");
    $attempts++;
    
    if ($guess < $secretNumber) {
        echo "Too low!
";
    } elseif ($guess > $secretNumber) {
        echo "Too high!
";
    } else {
        echo "Correct! You got it in $attempts attempts.
";
    }
} while ($guess != $secretNumber);
?>

Prime Number Checker

<?php
function isPrime($number) {
    if ($number < 2) return false;
    
    for ($i = 2; $i <= sqrt($number); $i++) {
        if ($number % $i == 0) {
            return false;
        }
    }
    return true;
}

// Find prime numbers between 1 and 50
echo "Prime numbers between 1 and 50:
";
for ($i = 1; $i <= 50; $i++) {
    if (isPrime($i)) {
        echo $i . " ";
    }
}
?>

Practice Exercise

Create a program that:

  • Generates a multiplication table for numbers 1-12
  • Uses nested loops
  • Skips multiples of 5 using continue
  • Stops the inner loop at 10 using break

Key Takeaways

  • Use if-else for conditional execution
  • Switch is good for multiple discrete values
  • Choose the right loop for your needs
  • Break and continue control loop flow
  • Alternative syntax is useful in templates