Saturday, October 6, 2012

foreach loop in php example

foreach loop in php 

 

Syntax

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

}
 
 
<?php
 
 
 $arr = array( 10, 20, 3, 40, 150);
foreach( $arr as $value )
{
  echo " $value <br />";
} 


//


$lang = array('php','java','c','c#','.net','perl');
echo "Your output here <br>"; 
 foreach( $lang as $val )
{
  echo " $val <br />";
} 

Do while loop in php

// Do While loop in php

Syntax

do
{
   code to be executed;
}while (condition); 
 
 
<?php
//print 1 to 10 number
$a = 1; 
do
{ 
echo "<br>".$a; 
 $a++; 
}while( $a < 10 );

?>
 

While loop in php examples



//  How to use while loop in php.


Syntax

while (condition)
{
    code to be executed;
}
 
 
<?php
// print  1 to 5  
$a=1;
while ($a<=5)
{
echo "\t ".$a;
$a=$a+1;
 
} 
 
?> 

Type of loop in php

There is mainly four type of loops.
Loops  are used to execute the same block of code a specified number of times in php.
 
1. for loop.
2. while loop.
3. Do-while loop.
3. foreach loop.


Syntax


for (initialization; condition; increment)
{
  code to be executed;
}


<?php 
// print  1 to 10 number 
for( $i=0; $i<10; $i++ )
{
echo "<br>".$i;
 
}
///////////////////
 
 
//Sum of ten number 
 
 
$sum = 0;
for( $i=0; $i<10; $i++ )
{
echo "<br>".$i;
$sum=$sum+$i;
}

echo " Total of 10 number =".$sum; 
 
?>