Lesson 5: Control Structures

Control structures in PHP enable developers to implement decision-making and repetitive tasks. This lesson covers conditional statements (if-else, switch-case) and loops (for, while, do-while, foreach) in detail, with examples and use cases.


5.1 If-Else Statements

What is an If-Else Statement?

  • If-else statements execute a block of code based on a condition.
  • Syntax:
  • if (condition) {
    // Code to execute if condition is true
    } elseif (another_condition) {
    // Code to execute if another_condition is true
    } else {
    // Code to execute if no condition is true
    }

Example: Simple If-Else

$age = 20;

if ($age >= 18) {
echo "You are eligible to vote.";
} else {
echo "You are not eligible to vote.";
}

Example: If-Elseif-Else

$score = 85;

if ($score >= 90) {
echo "Grade: A";
} elseif ($score >= 75) {
echo "Grade: B";
} else {
echo "Grade: C";
}


5.2 Switch-Case Statements

What is a Switch-Case Statement?

  • A switch-case statement evaluates a variable against multiple possible values and executes corresponding code.
  • Syntax:
  • switch (variable) {
    case value1:
    // Code to execute if variable equals value1
    break;
    case value2:
    // Code to execute if variable equals value2
    break;
    default:
    // Code to execute if no case matches
    }

Example: Switch-Case

$day = "Tuesday";

switch ($day) {
case "Monday":
echo "Start of the work week!";
break;
case "Friday":
echo "Almost weekend!";
break;
case "Saturday":
case "Sunday":
echo "It's the weekend!";
break;
default:
echo "Just another weekday.";
}


5.3 Loops

Why Use Loops?

Loops allow repetitive execution of code blocks as long as a specified condition is met.


5.3.1 For Loop

Syntax

for (initialization; condition; increment/decrement) {
// Code to execute
}

Example: Print Numbers

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

Example: Multiplication Table

for ($i = 1; $i <= 10; $i++) { echo "5 x $i = " . (5 * $i) . "
";
}

5.3.2 While Loop

Syntax

while (condition) {
// Code to execute
}

Example: Print Even Numbers

$num = 2;

while ($num <= 10) { echo "Even Number: $num
";
$num += 2;
}

Example: Factorial Calculation

$n = 5;
$factorial = 1;

while ($n > 0) {
$factorial *= $n;
$n--;
}

echo "Factorial: $factorial";


5.3.3 Do-While Loop

Syntax

do {
// Code to execute
} while (condition);

Example: Print Numbers

$num = 1;

do {
echo "Number: $num
";
$num++;
} while ($num <= 5);

Difference Between While and Do-While

  • In a while loop, the condition is checked before the first iteration.
  • In a do-while loop, the code executes at least once, even if the condition is false.

5.3.4 Foreach Loop

Purpose

  • Designed specifically for iterating over arrays.

Syntax

foreach ($array as $value) {
// Code to execute
}

Example: Iterate Over Array

$fruits = array("Apple", "Banana", "Cherry");

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

Example: Key-Value Pairs

$person = array("Name" => "Alice", "Age" => 25, "City" => "New York");

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


Activities and Exercises

  1. If-Else Statement:
    • Write a script to determine whether a given year is a leap year or not.
  2. Switch-Case Statement:
    • Create a script that takes a number (1–7) and outputs the corresponding day of the week.
  3. Loops:
    • Use a for loop to print the first 10 Fibonacci numbers.
    • Write a while loop that prints all odd numbers between 1 and 20.
    • Use a foreach loop to display all items in an associative array of student names and grades.

Assignment

Create a PHP script that:

  1. Uses an if-else statement to check whether a number is positive, negative, or zero.
  2. Uses a switch-case statement to output the month name when given a number (1–12).
  3. Uses a for loop to calculate the sum of numbers from 1 to 100.
  4. Uses a while loop to find the largest power of 2 less than a given number.
  5. Uses a foreach loop to display a list of products with their prices.

Summary

Control structures are crucial in PHP for decision-making and iteration. The concepts covered in this lesson form the backbone of logical programming in PHP and will be extensively used in real-world applications. Let me know if you'd like additional examples or exercises!

You said:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *