PHP Loops
Loops in PHP are used to run the same part of code a specified number of times.
PHP for Loop
The for loop executes a block of code again and again for a specified number of times.
Syntax
for (init; condition; increment) { code to be executed; }
PHP for loop Parameters:
- init: It’s set a counter value.
- condition: Evaluated for each loop iteration. If it considers TRUE, the loop continues. If it considers FALSE, the for loop ends.
- increment: Mostly used to increment a counter value.
Example
for ($x = 0; $x <= 30; $x+=5) { echo "The number is: $x <br>"; }
Output
The number is: 0
The number is: 5
The number is: 10
The number is: 15
The number is: 20
The number is: 25
The number is: 30
The number is: 5
The number is: 10
The number is: 15
The number is: 20
The number is: 25
The number is: 30
The foreach Loop
The PHP foreach loop is used to loop through arrays.
Syntax
foreach ($array as $value) { code to be executed; }
Example
$fruits = array("apple", "kiwi", "mango", "banana"); foreach ($fruits as $value) { echo "$value <br>"; }
Output
apple
kiwi
mango
banana
kiwi
mango
banana
Example
$hbhero = array( "name" => "John Parker", "email" => "jp28@mail.com", "age" => 28 ); // Loop through superhero array foreach($hbhero as $key => $value){ echo $key . " : " . $value . "<br>"; }
Output
name : John Parker
email : jp28@mail.com
age : 28
email : jp28@mail.com
age : 28