PHP Loops
Loops execute the same code multiple times.
While Loop:
1 2 3 |
While(condition){ //repeat something while the condition is true } |
Example:
1 2 3 4 5 6 |
$i =0; while($i < 10){ $i++; echo $i.' '; } |
Here loop will run until $i is less than 10.
Continue Keyword:
1 2 3 4 5 6 7 8 9 |
$i =0; while($i < 10){ $i++; if($i % 2){ continue; } echo $i.' '; } |
This condition will fail when $i is odd number. So when $i is odd the condition will fail and it will go back to the top of the loop.
Do…While Loop
1 2 3 |
do{ //Repeat as long as condition is true } while(condition); |
The difference between while and do while loop is that do while loop is always executed at least once even if the condition never true.
1 2 3 4 5 6 |
$i =100; do{ $i++; echo $i.' '; } while($i < 10 ); |
Using for loop:
The main advantage of using a for loop that the chances of going to the infinite loop are less.
1 2 3 |
for(initial counter; condition; increment){ //repeat something while condition is true } |
Example
1 2 3 4 |
for ($i = 0; $i <= 10; $i++) { echo "The number is: $i "; } |
foreach : Loop through Array
Accessing Array Values
1 2 3 |
foreach($arrayName as $value){ //Do something with $value } |
Example
1 2 3 4 5 |
$name = array("kriti", "dev", "sam", "matu"); foreach ($name as $value) { echo "$value "; } |
- A foreach loop accesses each array element, and it is similar to for loop for indexed array.
- foreach loop is only used when you have to process everything in order.
- for loop is better when you don’t want to loop through the whole array.
- foreach loop is mainly useful for an associative array.