Belajar PHP Part 22 : While Loop

while loop

While Loop

  • While Loop versi perulangan yang lebih sederhana dibanding for loop
  • Di While loop, hanya terdapat kondisi perulangan, tanpa ada init statement dan post statement

Syntax
while (condition) {
    //block execute
}

Contoh Code While Loop

$counter = 1; 

while ( $counter <= 10 ) {
    echo "Hello While Loop " . $counter . PHP_EOL;
    $counter++;
}

while loop

Syntax Alternative While Loop

$counter = 1 ;

while ( $counter <= 10 ) :
    echo "Hello While Loop " . $counter . PHP_EOL;
    $counter++;
endwhile;

Do While

  • Do While Loop adalah perulangan yang mirip dengan while
  • Perbedaanya hanya berada pada pengecekan kondisi
  • Pengecekan kondisi di while loop dilakukan di awal sebelum perulangan dilakukan, sedangkan di do while loop dilakukan setelah perulangan di lakukan
  • Oleh karena itu dalam do while loop, minimal pasti sekali perulangan dilakukan walapun kondisi tidak bernilai true
$counter = 1;

do  {
    echo "Ini adalah do while ke-". $counter . PHP_EOL;
    $counter++;
} while ( $counter <= 10 );
do while


Next Post Previous Post
No Comment
Add Comment
comment url