Loops in PHP

“While [SOME CONDITION] is true, execute [CODE]. if [SOME CONDITION] becomes false, move on.”

  • A true/false condition.
  • A statement that moves that condition towards becoming false.

Types of Loops in PHP

WHILE LOOPS FOR LOOPS FOR EACH LOOPS

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

while ($i < 10){
    $i++;
}

for ($i =0; $i < 10; $i++){
    echo $i
}
// infinite loop example
for ($i =10; $i > 0 ; $i++){
    echo $i
}

for ($i = 0; $i < sizeof($colors); $i++){
    echo '<p>' . $colors[$i] . '</p>';
}

// for each loop to traverse arrays

foreach( array as item) {
    // do something with item
}

foreach($colors as $color ){
    echo "<p>$color</p>";
}

foreach (array as key => value) {
    // do something with key and value
}

//associative arrays
$home_towns = array(
    'Joe' => 'Punjab, PU',
    'Imran' => 'Karachi, KHI',
);

foreach($home_towns as $name => $town ){
    echo "<p>$name live in $town</p>";
}
Previous
Next