logo CBCE Skill INDIA

Welcome to CBCE Skill INDIA. An ISO 9001:2015 Certified Autonomous Body | Best Quality Computer and Skills Training Provider Organization. Established Under Indian Trust Act 1882, Govt. of India. Identity No. - IV-190200628, and registered under NITI Aayog Govt. of India. Identity No. - WB/2023/0344555. Also registered under Ministry of Micro, Small & Medium Enterprises - MSME (Govt. of India). Registration Number - UDYAM-WB-06-0031863

What are the 4 types of PHP loops?


4 types of PHP Loops

PHP supports several types of loops that allow you to repeatedly execute a block of code. As of my last update in January 2022, PHP has four main types of loops:

 

  1. for loop:

    for (initialization; condition; increment/decrement) {
        // code to be executed
    }

    Example:

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

    This loop initializes a counter variable, checks a condition, executes the code block, and increments the counter in each iteration.

  2. while loop:

    while (condition) {
        // code to be executed
    }

    Example:

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

    The while loop continues to execute the code block as long as the specified condition is true.

  3. do-while loop:

    do {
        // code to be executed
    } while (condition);

    Example:

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

    The do-while loop is similar to the while loop, but it always executes the code block at least once before checking the condition.

  4. foreach loop:

    foreach ($array as $value) {
        // code to be executed
    }

    Example:

    $colors = array("red", "green", "blue");
    foreach ($colors as $color) {
        echo $color;
    }

    The foreach loop is used to iterate over arrays or other iterable objects, assigning each element to the specified variable ($value in the example).

 

These loops provide flexibility in handling different scenarios, and the choice of which loop to use depends on the specific requirements of your code. Keep in mind that PHP may introduce new features or loops in subsequent versions, so it's a good idea to refer to the official PHP documentation for the latest information.

 

Thank you.

Popular Post:

Give us your feedback!

Your email address will not be published. Required fields are marked *
0 Comments Write Comment