
Please support if you like my work by payment through upi: sinhamit@icici or payment by bank
account name: Amit Kumar Sinha,
account number: 2646728782
IFSC code: KKBK0005660
SWIFT: KKBKINBB
Different Kinds of Loops in Category: PHP by amit
🕙 Posted on 2023-06-05 at 19:52:02 Read in Hindi ...
LOOPs
Loops empowers you to get data from the database in an organized manner, when you don't know how much data you need. For example, you can see latest topics mentioned in tutorial page. Also, when you click on any category, tutorials related to that category is shown in the same page. You can view all topics uploaded on this website, on site page. Loops also help you to paginate your data, as you can see in tutorial page.
Loops are very helpful to control data-flow structures in specific manner, as per your need. A LOOP is a block of codes which will be executed repeatedly to specified extent (number of times), on fulfilment of certain condition. It means that in a loop, there should be three requisites: (1) Initialization, (2) Conditional expression, and (3) Iteration.
Initialization
Initialization is declaring a variable name, for example, $num to initialize the loop. The value assigned to $num must be of numeric (preferably, integer) data-type, and can be either 0
(zero) or 1 to move the loop in positive ('right') direction, or total number of items (that is, maximum count of an array) to move the loop in negative ('left') direction.
Moving towards right: 0 1 2 3 4 5 6 7 8 9 ...
Moving towards left: from 9 to 0 (opposite direction of above)
Condition
A condition checks whether the value of variable name, $num is < (less than) or <= (less than or equal to) or > (greater than) or >= (greater than or equal to) from total number of items (see Comparison Operators). When the condition is true
, the block of codes inside the {}
curly braces will be executed.
Iteration
Iteration means the steps in which you want to move the loop, that is, either to increase or to decrease the value of the variable name, $num. It is important to note that you should not use constant for initialization. Also, when certain things are simple (integer data-type), they work better. You can increase or decrease a loop with two or more steps, as explained in following examples, but generally ++
(increment) or --
(decrement) operator is used to iterate one step.
Syntax for different kinds of LOOPs
There are generally four kinds of loops: while(){}
, do {} while()
, for(){}
, and foreach(){}
.
while() {} loop
while() {} loop is generally used to fetch data from the database. DATABASE drivers are different from PHP array pointer. Every array has an internal pointer to its 'current' element, which is initialized to the first element inserted into the array. Similarly, data from a database is imported as query (object data-type) and then converted into associative array.
Each row from that associative array is fetched by the while() {}
loop. However, a simple while() {} loop is explained as below:
<?php
$num = 0; // initialization
while
( $num <= 10 ) { // Condition to be checked is inside parentheses
echo $num . ' '; // block of codes must be above following iteration.
$num = $num + 1; // Iteration: you can add 2 or other integer value.
}?>
In the above example, the while
(reserved keyword) is used to loop. You can use <br /> HTML line-break element to output each of above numbers in a new line. It is important to note that the value of variable $num is changed every time, when the block of codes inside {}
curly braces is executed. Thus, you should be careful to reset the value of $num, in one REQUEST RESPONSE CYCLE. Let't see another example:
<?php
$num = 20;
while
( $num >= 0 ) {
echo $num . '<br />';
$num -= 2; // same as $num = $num - 2;
}?>
In the above example, the variable $num is initialized (assigned) with value 20. You can initialize it with 0
(zero) and then change the condition to $num <= 20. Also, you have to change the iteration to $num += 2;. Then the output will be in reverse order of following result. There are many ways, in which you can play and experiment to get different results.
18
16
14
12
10
8
6
4
2
0
do{} while() loop
do{} while() is special kind of while loop, in which the block of codes inside the {}
curly braces is executed at least once, no matter the condition inside the parentheses after the while
(reserved keyword) is false. Thereafter, the condition is checked, and when it is true, the do{} while()
will execute the block of codes inside that curly braces, till the condition becomes false
.
<?php
$num = 0.2;
do
{
echo $num . ' '; // do-while loop outputs at least 0.2 first time
$num++; // same as $num = $num + 1;
} while
( $num <= 10 ); // Outputs 0.2 1.2 2.2 3.2 4.2 5.2 6.2 7.2 8.2 9.2
echo $num; // Outputs 10.2?>
In the above example, the variable $num is first initialized (assigned) with value 0.2
. It is important that the value must be a numeric data-type or null
. You must attach ; (semi-colon) after the end of do {} while() loop, otherwise ERROR will be shown. The last line before the closing PHP tag, is intentionally placed to explain that ; (semi-colon) is very important in do-while loop. Also, the value of the variable $num can be displayed or used after the all four kinds of loops (described herein).
for() {} loop
for() {}
loop is same as while loop, but all three requisites mentioned above, that is, initialization, condition, and iteration have to be placed inside the parentheses ()
just after the for
(reserved keyword). for() {} and foreach() {} loops are generally used with PHP arrays.
You can use array functions, for example, current()
, next()
, prev()
, end()
, reset()
, and each()
to move or to get location of the pointer in a PHP array. In this way, you can paginate topics in your CMS or your website. Simple for() {} loop is explained as below:
<?php
for
( $num = 0; $num <= 10; $num++ ) {
echo $num . ' ';
}
echo $num;?>
foreach() {} loop
foreach() {}
loops are used only to get data from an arrays. It means that, a foreach() {} loop is different from while() {}, do{} while() and for() {} loops (as described above). foreach() {} loops are of two kinds: (1) to get values of respective items of an array, and (2) to get keys and their respective values from an array.
<?php
$my_array = [ 2, 3, 5, 7, 11, 13, 17, 19 ];
foreach
( $my_array as
$my_item ) {
echo $my_item . ' ';
}?>
The foreach() {} loop does not need three requisites as mentioned above. An array has fixed number of items. Therefore, the foreach() {} automatically determines the initialization, conditional expression and iteration of loop. In the above example, you can see that only values of each item is output.
However, in the following two examples, (first is an indexed array, and second is an associative array) keys and their respective values are output. The arrows (⇒) shown in the output are not returned from the PHP interpreter, but they are UNICODE symbols.
<?php
$my_array = [ 2, 3, 5, 7, 11, 13, 17, 19 ];
foreach
( $my_array as
$key_name =>
$my_item ) {
echo $key_name . '⇒' . $my_item . ' ';
}?>
<?php
$my_array = [ 'a' => 2, 'b' => 3, 'c' => 5, 'd' => 7, '0' => 11, false => 13, '' => 17, null => 19 ];
foreach
( $my_array as
$key_name =>
$my_item ) {
echo $key_name . '⇒' . $my_item . ' ';
}?>
In the above example, you can see that sixth item replaces the fifth item, and eight item replaces the seventh item of the associative array. This is because false
as well as '0' are evaluated as 0
, and null
is evaluated as '' (empty string).
Infinite Loops
When the conditional expression inside the parentheses of while or for loop is always evaluated as true
, then the PHP interpreter or compilers in other programming languages cannot end the LOOP. This kind of loops are called infinite or indefinite loops. You should carefully examine codes in your script, and must always avoid infinite loops.
<?php while
( true ) { echo 'Infinite WHILE LOOP<br />'; } ?>
<?php for
( ; ; ) { echo 'Infinite FOR LOOP<br />'; } ?>
Sometimes, conditional expression containing == (equal to) operator is mistakenly replaced by = (assignment operator), which can create infinite loops. An example of this kind of loop is as follows:
<?php for
( $num = 0; $num = 1; $num++) { echo 'Infinite FOR LOOP<br />'; } ?>
Leave a Comment:

Amit Sinha March 2nd, 2023 at 9:30 PM
😃 😄 😁 😆 😅 😂 😉 😊 😇 😍 😘 😚 😋 😜 😝 😶 😏 😒 😌 😔 😪 😷 😵 😎 😲 😳 😨 😰 😥 😢 😭 😱 😖 😣 😞 😓 😩 😫 😤

Ribhu March 3rd, 2023 at 9:30 PM
🐵 🐒 🐶 🐩 🐺 🐱 🐯 🐅 🐆 🐴 🐎 🐮 🐂 🐃 🐄 🐷 🐖 🐗 🐽 🐏 🐑 🐐 🐪 🐫 🐘 🐭 🐁 🐀 🐹 🐰 🐇