LOOPING STRUCTURE | BCA SEM 02 PHP BKNMU JUNAGADH

Looping Structures in PHP

Looping Structures in PHP

In PHP, Looping Structures allow developers to execute a block of code repeatedly, either a specified number of times or until a condition is met. These structures are essential for iterating through data or performing repetitive tasks.

Types of Looping Structures in PHP

while Loop

Repeats as long as the specified condition evaluates to true.

Syntax:
while (condition) {
    // Code to execute
}

Example:
$count = 1;

while ($count <= 5) {
    echo "Count is $count. ";
    $count++;
}

do-while Loop

Executes the block of code at least once, and then repeats as long as the condition is true.

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

Example:
$count = 1;

do {
    echo "Count is $count. ";
    $count++;
} while ($count <= 5);

for Loop

Repeats a block of code a specific number of times, controlled by an initializer, condition, and increment/decrement.

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

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

foreach Loop

Iterates over each element in an array. It is specifically designed for arrays and objects.

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

Example:
$colors = ["Red", "Green", "Blue"];

foreach ($colors as $color) {
    echo "Color: $color. ";
}

Using Key-Value Pairs:
$fruits = ["a" => "Apple", "b" => "Banana", "c" => "Cherry"];
foreach ($fruits as $key => $value) {
    echo "$key: $value. ";
}

break and continue Statements

break: Exits the loop entirely.
continue: Skips the rest of the current iteration and moves to the next iteration.

Example with break:
for ($i = 1; $i <= 10; $i++) {
    if ($i == 5) {
        break;
    }
    echo "$i ";
}

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

Nested Loops

Loops can be nested within each other.

Example:
for ($i = 1; $i <= 3; $i++) {
    for ($j = 1; $j <= 2; $j++) {
        echo "Outer: $i, Inner: $j. ";
    }
}

Summary Table of Looping Structures

Loop Type Use Case Runs at Least Once?
while When the number of iterations is unknown. No
do-while When the block must run at least once. Yes
for When the number of iterations is known. No
foreach When iterating through arrays/collections. No

Post a Comment

Thanks for comment.

Previous Post Next Post