डिप्लोमा इन ऑफिस मैनेजमेंट एण्ड अकाउटिंग

डिप्लोमा इन ऑफिस मैनेजमेंट एण्ड अकाउटिंग

Full Stack Web Development with Laravel

Full Stack Web Development with Laravel

Affiliate Program

Affiliate Program

PHP loop

First of all, think about what you have learned sequentially, and then think about what you can not do with what you have learned so we need to use the loop.
Actually, we can not repeat any statement very easily, can write a statement many times either by writing or copying that statement but there is a program that will take too many times.

for example, we want to display the country name "India" 10 times, is there anything that we can use efficiently, so there is a perfect use of the loop.

In PHP, there are four types of loops.

  1. for loop
  2. while loop
  3. do-while loop
  4. foreach loop

for loop

for($x=1; $x <= 10; $x++){
echo "India";
}

while loop

$n=1;
while($n<=10){
echo "India";
$n++;
}

do-while loop

$n=1;
do{
echo "India";
$n++;
}
while($n <= 10);

foreach loop

foreach loop is used in looping over an array


$persons=["aman", "kamal", "ajay", "rohit"];
foreach($persons as $person){
echo $person."<br>";
}

Nested loop

when a loop is written within another loop that is called a nested loop

for($n=1; $n<=3; $n++){
   for($x=1; $x<=3; $x++){
echo "*";
}
echo "<br>";
}

output:


***
***
***

break & continue statement

break keyword terminates execution of current loop
for example we want to terminates a loop when loop value is 5

for($n=1; $n<=10; $n++){
if($n==5){
   break;
}
echo $n."<br>";
}


output will be like this:


1
2
3
4

continue keyword do jump to next steps in the current loop
for example we want to use continue statement in a loop as loop value react at 5

for($n=1; $n<=10; $n++){
if($n==5){
   continue;
}
echo $n."<br>";
}


the output will be like this:


1
2
3
4
6
7
8
9
10
© 2016 - 2023, All Rights are Reserved.