Thursday, August 17, 2017

PHP For Loop


PHP for loop can be use to execute/run the particular set of code for specified number of times. For loop mostly use in php scripts.











Syntax :
for(initialization; condition; increment/decrement){  
//code to be executed here 
}

1. Initialization : it is evaluated (executed) once unconditionally at the beginning of the loop.
2. Condition : In the beginning of each iteration, condition is evaluated. If it evaluates to TRUE, the loop continues and the nested statement(s) are executed. If it evaluates to FALSE, the execution of the loop ends.
3.Increment/Decrement : At the end of each iteration, it is evaluated (executed).Based on condition it will increment and decrement the initialize variable.

Example :
<?php  
for($a=1;$a<=5;$n++){  
echo "$a<br/>";  
}  
?>

Output:
----------------------
1
2
3
4
5

PHP Nested For Loop:
When we use loop inside the loop is called as nested for loop. Similary we can use the nested concept in for loop. Let's see the below example.

<?php
$n=5;
for($i=1; $i<=$n; $i++)
{
for($j=1; $j<=$i; $j++)
{
echo ' * ';
}
echo '<br>';
}
for($i=$n; $i>=1; $i--)
{
for($j=1; $j<=$i; $j++)
{
echo ' * ';
}
echo '<br> ';
}
?>

Output:
------------------

* * 
* * * 
* * * * 
* * * * * 
* * * * * 
* * * * 
* * * 
* * 
*

PHP For Each Loop :
1. The foreach loop construct provides the easy way to iterate the array element only.
2. we can't use it on a variable with a different data type or an uninitialized variable, that leads to an issue an error. 

Syntax:
foreach( $array as $var ){  
 //code to be executed here 
}  
?>

Example:
<?php
$number = array("one", "two", "three");
foreach( $number as $arr ){  
  echo "number is: $arr<br />";  
} 

?>

Output:
------------
number is: one
number is: two
number is: three


No comments:

Post a Comment