دوره while در PHP
- Previous Page PHP Switch
- Next Page PHP For Loop
حلقه while PHP در حالی که شرط مشخص شده صحیح باشد، بلوک کد را اجرا میکند.
حلقه PHP
در حالی که شما در حال نوشتن کد هستید، اغلب نیاز به اجرای دوباره بلوک کد دارید. ما میتوانیم از حلقه برای انجام چنین وظایفی استفاده کنیم، به جای اضافه کردن چند خط تقریباً مشابه به اسکریپت.
در PHP، ما دستورالعملهای حلقه زیر را داریم:
- while - تا زمانی که شرط مشخص شده صحیح باشد، بلوک کد را تکرار کنید
- do...while - ابتدا یک بلوک کد را اجرا کنید، سپس تا زمانی که شرط مشخص شده صحیح باشد، تکرار کنید
- for - Loop the code block a specified number of times
- foreach - Traverse each element in the array and loop the code block
دوره while در PHP
As long as the specified condition is true, the while loop will execute the code block.
Syntax
while (condition is true) { The code to be executed; }
The following example first sets the variable $x to 1 ($x=1). Then, execute the while loop as long as $x is less than or equal to 5. Each time the loop runs, $x will increment by 1:
Example
<?php $x=1; while($x<=5) { echo "This number is: $x <br>"; $x++; } ?>
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 { The 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, check the condition ($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); ?>
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 execute at least one statement, even if the condition test fails on the first attempt.
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); ?>
The next section will explain the for loop and foreach loop.
- Previous Page PHP Switch
- Next Page PHP For Loop