Κύκλος while στο PHP

Ο κύκλος while του PHP εκτελεί το τμήμα κώδικα όσο η συνθήκη είναι αληθής.

Κύκλοι PHP

Κατά τη διάρκεια της συγγραφή σας, συχνά χρειάζεστε να εκτελέσετε το ίδιο τμήμα κώδικα πολλές φορές. Μπορούμε να χρησιμοποιήσουμε κύκλους για να εκτελέσουμε τέτοιες εργασίες, αντί να προσθέσουμε αρκετές γραμμές κώδικα που είναι σχεδόν ίδιες στο σενάριο.

Στο PHP, έχουμε τις εξής εντολές κύκλου:

  • while - Επαναλάβετε τον κύκλο όσο η συνθήκη είναι αληθής
  • do...while - Εκτελέστε πρώτα μια ενότητα κώδικα, και μετά επαναλάβετε τον κύκλο όσο η συνθήκη είναι αληθής
  • for - Loop the code block a specified number of times
  • foreach - Traverse each element of the array and loop the code block

Κύκλος while στο PHP

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

Syntax

while (condition is true) {
  Code to be executed;
}

The following example first sets the variable $x to 1 ($x=1). Then, the while loop is executed as long as $x is less than or equal to 5. Each time the loop runs, $x is incremented by 1:

Example

<?php 
$x=1; 
while($x<=5) {
  echo "This number is: $x <br>";
  $x++;
} 
?>

Run Example

PHP do...while loop

The do...while loop first executes the code block, then checks the condition, and if the specified condition is true, it repeats the loop.

Syntax

do {
  Code to be executed;
} while (condition is true);

The following example first sets the variable $x to 1 ($x=1). Then, the do while loop outputs a string, then increments the variable $x by 1. Then the condition is checked ($x is less than or equal to 5). As long as $x is less than or equal to 5, the loop will continue to run:

Example

<?php 
$x=1; 
do {
  echo "This number is: $x <br>";
  $x++;
} while ($x<=5);
?>

Run Example

Please note that the do while loop checks the condition only after executing the statements inside the loop. This means that the do while loop will always execute at least one statement, even if the condition test fails on the first try.

The following example sets $x to 6, then runs the loop,Then check the condition:

Example

<?php 
$x=6;
do {
  echo "This number is: $x <br>";
  $x++;
} while ($x<=5);
?>

Run Example

The next section will explain for loops and foreach loops.