Tags
Asked 3 years ago
13 Jul 2021
Views 247
Santiago

Santiago posted

Can we use for loop in PHP ?

Can we use for loop in PHP ?
sandip

sandip
answered Aug 19 '21 00:00

yes we can use for loop in PHP

for loop example code :

for($i=0;$i<=10;$i++){
echo $i." ";
}


it will give output 1 to 10 as below :

0 1 2 3 4 5 6 7 8 9 10 


for loop explained :
for (expr1; expr2; expr3)
expr1 is initialized once at the start of the loop. mostly expr1 is declare like $x=0 or $x=10
expr2 is expression which is evaluated in every loop if it return true loop continue , if it return false than it stop the loop , suppose $x>10 so for every iteration it check is it $x>10 or not if yes it continue to the loop or exit the loop
exp3 is the expression that also execute every time. suppose $x++ , it will increment the $x at every iteration
Mahesh Radadiya

Mahesh Radadiya
answered Aug 19 '21 00:00

except for loop in PHP , there are other type of loop aviliable also ,
all type of loop is work same manner in PHP

while


$x=0;
while($x<=10){
echo $x;
$x++;
}


it will print 0 to 10

do-while


$x=0;
do {
echo $x." ";
$x++;
}while($x<=10);

it will print 0 to 10 with do.. while loop same as while loop

foreach
foreach loop is a different way of looping
foreach loop work always with an array in PHP
below is an example for foreach loop :


$loop=array(0,1,2,3,4,5,6,7,8,9,10);
foreach($loop as $value){
echo $value;
}




above is very simple example of the use of loop , but it can be complex use of for and other type of loop in PHP



Post Answer