PHP Loops

8 min read

In the following chapters you will learn how to repeat code by using loops in PHP.

Дараагийн бүлгээс та PHP дээр Loop ашиглан кодыг хэрхэн давтах талаар сурах болно.


PHP Loops #

Often when you write code, you want the same block of code to run over and over again a certain number of times. So, instead of adding several almost equal code-lines in a script, we can use loops.

Ихэнхдээ та код бичихдээ ижил блок кодыг тодорхой удаа дахин дахин ажиллуулахыг хүсдэг. Тиймээс скриптэд бараг хэд хэдэн тэнцүү кодын мөр нэмэхийн оронд loops ашиглаж болно.

Loops are used to execute the same block of code again and again, as long as a certain condition is true.

Тодорхой нөхцөл үнэн бол л loops ижил кодын блокыг дахин дахин гүйцэтгэхэд ашигладаг.

In PHP, we have the following loop types:

PHP дээр бид дараах loop-ийн төрлүүдийг агуулдаг.

  • while – loops through a block of code as long as the specified condition is true

    while – loops заасан нөхцөл үнэн бол блок кодоор давтана

  • do...while – loops through a block of code once, and then repeats the loop as long as the specified condition is true

    do...while – loops кодын блокыг нэг удаа давтаж, дараа нь заасан нөхцөл үнэн бол хийсэн зүйлээ дахин давтана

  • for – loops through a block of code a specified number of times

    for – loops кодын багцыг заасан тоогоор давтах

  • foreach – loops through a block of code for each element in an array

    foreach – loops Багц дахь элемент тус бүрийн кодын блокыг давтана

The following chapters will explain and give examples of each loop type.

Дараах бүлгүүдэд давталтын төрөл тус бүрийг тайлбарлаж, жишээг өгөх болно.

The while loop – Loops through a block of code as long as the specified condition is true.

while давталт – Тодорхойлсон нөхцөл үнэн л бол блокийн кодоор дамжина.


The PHP while Loop #

The while loop executes a block of code as long as the specified condition is true.

while давталт нь заасан нөхцөл үнэн бол л блокийг ажиллуулдаг.

Syntax #

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

while (нөхцөлд үнэн) {

гүйцэтгэх код;

}

Examples

Жишээ

The example below displays the numbers from 1 to 5:

Доорх жишээнд 1-ээс 5 хүртэлх тоог харуулна:

Example #

Жишээ #

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

Example Explained – Эйлбарласан Жишээ #

  • $x = 1; – Initialize the loop counter ($x), and set the start value to 1

    $ x = 1; – Давталтын тоолуурыг эхлүүлж ($ x), эхлэх утгыг 1 болго

  • $x <= 5 – Continue the loop as long as $x is less than or equal to 5

    $ x <= 5 – $ x нь 5-аас бага эсвэл тэнцүү байвал давталтыг үргэлжлүүлнэ

  • $x++; – Increase the loop counter value by 1 for each iteration

    $ x ++; – Давталт бүрийн хувьд давталтын тоолуурын утгыг 1-ээр нэмэгдүүлнэ

This example counts to 100 by tens:

Энэ жишээг 100 араваар тоолно:

Example #

Жишээ #

<?php $x = 0; while($x <= 100) { echo "The number is: $x <br>"; $x+=10; }

Example Explained #

  • $x = 0; – Initialize the loop counter ($x), and set the start value to 0

    $ x = 0; – Давталтын тоолуурыг эхлүүлж ($ x), эхлэх утгыг 0 болго

  • $x <= 100 – Continue the loop as long as $x is less than or equal to 100

    $ x <= 100 – $ x нь 100-аас бага эсвэл тэнцүү байвал давталтыг үргэлжлүүлнэ

  • $x+=10; – Increase the loop counter value by 10 for each iteration

    $ x + = 10; – Давталт бүрийн хувьд давталтын тоолуурын утгыг 10-аар нэмэгдүүлнэ

The do...while loop – Loops through a block of code once, and then repeats the loop as long as the specified condition is true.

do...while давталт – Блокын кодоор нэг удаа давтаж, заасан нөхцөл үнэн л бол давталтыг давтана.


The PHP do…while Loop #

The do...while loop will always execute the block of code once, it will then check the condition, and repeat the loop while the specified condition is true.

do...while давталт нь кодын блокыг үргэлж нэг удаа ажиллуулах бөгөөд дараа нь нөхцлийг шалгаж, заасан нөхцөл үнэн байхад давталтыг давтана.

Syntax #

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

хийх {

гүйцэтгэх код;

} while (нөхцөл үнэн);

Examples #

Жишээ #

The example below first sets a variable $x to 1 ($x = 1). Then, the do while loop will write some output, and then increment the variable $x with 1. Then the condition is checked (is $x less than, or equal to 5?), and the loop will continue to run as long as $x is less than, or equal to 5:

Доорх жишээнд эхлээд $ x гэсэн хувьсагчийг 1 болгож тохируулсан ($ x = 1). Дараа нь do while давталт нь зарим гаралтыг бичээд дараа нь $ x хувьсагчийг 1-ээр нэмэгдүүлнэ. Дараа нь нөхцөлийг шалгана ($ x-ээс бага эсвэл 5-тай тэнцүү үү?), Давталт үргэлжлүүлэн ажиллана. $ x нь 5-аас бага буюу тэнцүү:

Example #

Жишээ #

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

This example sets the $x variable to 6, then it runs the loop, and then the condition is checked:

Энэ жишээ нь $ x хувьсагчийг 6 болгож, дараа нь давталтыг ажиллуулж, дараа нь нөхцөлийг шалгана:

Example #

Жишээ #

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

The for loop – Loops through a block of code a specified number of times.


The PHP for Loop #

The for loop is used when you know in advance how many times the script should run.

Syntax #

for (init counter; test counter; increment counter) {
  code to be executed for each iteration;
}

Parameters:

  • init counter: Initialize the loop counter value
  • test counter: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it evaluates to FALSE, the loop ends.
  • increment counter: Increases the loop counter value

Examples #

The example below displays the numbers from 0 to 10:

Example #

<?php for ($x = 0; $x <= 10; $x++) { echo "The number is: $x <br>"; } ?>

Example Explained #

  • $x = 0; – Initialize the loop counter ($x), and set the start value to 0
  • $x <= 10; – Continue the loop as long as $x is less than or equal to 10
  • $x++ – Increase the loop counter value by 1 for each iteration

This example counts to 100 by tens:

Example #

<?php for ($x = 0; $x <= 100; $x+=10) { echo "The number is: $x <br>"; } ?>

Example Explained #

  • $x = 0; – Initialize the loop counter ($x), and set the start value to 0
  • $x <= 100; – Continue the loop as long as $x is less than or equal to 100
  • $x+=10 – Increase the loop counter value by 10 for each iteration

The foreach loop – Loops through a block of code for each element in an array.

foreach давталт – Багцын элемент тус бүрийн кодын блокыг давтана.


The PHP foreach Loop #

The foreach loop works only on arrays, and is used to loop through each key/value pair in an array.

foreach давталт нь зөвхөн array дээр ажилладаг бөгөөд array дахь түлхүүр / утгын хос бүрээр давталт хийхэд ашиглагддаг.

Syntax #

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

foreach ($ array $value) {

гүйцэтгэх код;

}

For every loop iteration, the value of the current array element is assigned to $value and the array pointer is moved by one, until it reaches the last array element.

Давталт бүрийн хувьд array одоогийн элементийн утгыг $value өгч array заагчийг  сүүлчийн элементэд хүрэх хүртэл нэгээр шилжүүлнэ.

Examples #

Жишээ #

The following example will output the values of the given array ($colors):

Дараах жишээ нь өгөгдсөн array утгыг ($colors) гаргана:

Example #

Жишээ #

<?php $colors = array("red", "green", "blue", "yellow"); foreach ($colors as $value) { echo "$value <br>"; } ?>

The following example will output both the keys and the values of the given array ($age):

Дараах жишээ нь өгөгдсөн array түлхүүрүүд болон утгуудыг хоёуланг нь гаргах болно ($age):

Example #

Жишээ #

<?php $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43"); foreach($age as $x => $val) { echo "$x = $val<br>"; } ?>

PHP Break #

You have already seen the break statement used in an earlier chapter of this tutorial. It was used to “jump out” of a switch statement.

Энэ гарын авлагын өмнөх бүлэгт ашигласан break мэдэгдлийг та өмнө нь харсан. Үүнийг switch мэдэгдэлээс “jump out”” ашигласан болно.

The break statement can also be used to jump out of a loop.

break мэдэгдлийн  давталтаас jump out ашиглаж болно.

This example jumps out of the loop when x is equal to 4:

Энэ жишээ нь x 4-тэй тэнцэх үед давталтаас үсрэх болно.

Example #

Жишээ #

<?php for ($x = 0; $x < 10; $x++) { if ($x == 4) { break; } echo "The number is: $x <br>"; } ?>

PHP Continue #

The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.

continue мэдэгдэл нь заасан нөхцөл үүссэн тохиолдолд нэг давталтыг (in the loop) эвдэж, давталтын дараагийн давталтаар үргэлжлүүлнэ.

This example skips the value of 4:

Энэ жишээ нь 4-ийн утгыг алгасах болно.

Example #

Жишээ #

<?php for ($x = 0; $x < 10; $x++) { if ($x == 4) { continue; } echo "The number is: $x <br>"; } ?>

Break and Continue in While Loop #

You can also use break and continue in while loops:

Та break хийж continue давтаж while хийж болно.

Break Example #

Үлгэр Жишээ #

<?php $x = 0; while($x < 10) { if ($x == 4) { break; } echo "The number is: $x <br>"; $x++; } ?>

Continue Example #

<?php $x = 0; while($x < 10) { if ($x == 4) { $x++; continue; } echo "The number is: $x <br>"; $x++; } ?>

Powered by BetterDocs

Leave a Reply