Blog > detail

Just my tiny mind

Five Methods for PHP Looping

26-2-2012 Admin General 2 Comments

Five Methods for PHP Looping

Looping is one of the most common process used by web developer while building a site. In this article, I will try to shareFive Methods for PHP Looping processes.


Frist, You can use "while":

while(condition){do something}

Exp in php:


$cond = 1;

while($cond >= 10){echo $cond;$cond++;}


The above code will print "12345678910".


Second, You can use "for":

for(condition){do something}

Exp in php:


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


The above code will print "12345678910".


Third, you can use "do-while":

do{do something}while(condition);

Different with while, do-while will execute the command first, then check the condition. Even if the condition is not match, the do-while will execute the command once.

Exp in php:


$i = 1;

do {echo $i;$i++;} while ($i <= 10);


The above code will print "12345678910".

Exp in php:


$i = 1;

do {echo $i;} while ($i = 10);


The above code will print "1".


Fourth, you can use "foreach":

foreach(array as $keys => $vasl){do something}

Foreach is used to print out an array.

Exp in php:


$arrs = array("septiadi","hasan","muhammad");

foreach ($arrs as $keys => $vals) {

echo $keys."=>".$vals." ";

}


The above code will print "0=>septiadi 1=>hasan 2=>muhammad".


Fifth, you can use "goto":

location:.... goto location; or goto location;.... location:

Exp in php:


$i=1;

loc:

echo $i;

goto loc;


The above code will print "1" continously.

Exp in php:


$i=1;

loc:

echo $i;$i++;

if($i>10)goto loc2;

goto loc;

loc2:


The above code will print "12345678910".


Currently there are only Five Methods for PHP Looping processes that I know. There is posibility to do different way than the Five Methods for PHP Looping. May be you are the one that find the sixth method :D.


Good luck.


Five Methods for PHP Looping Five Methods for PHP Looping Five Methods for PHP Looping

Five Methods for PHP Looping Five Methods for PHP Looping Five Methods for PHP Looping

Five Methods for <a href=PHP Looping" width="1" height="1" />

word word

Five Methods for PHP Looping

Five Methods for PHP Looping

Five Methods for PHP Looping