PHP for Loop

The for loop in PHP is used when you know in advance how many times you need to execute a block of code. It is particularly useful for iterating a known number of times, and it offers more control over loop iterations compared to while and do...while loops.


Syntax


for (initialization; condition; increment/decrement) {
    // Code to be executed on each iteration
}


  • initialization: This expression is executed once at the beginning of the loop. It usually sets a counter variable.
  • condition: The loop continues to run as long as this condition evaluates to true. It is evaluated before each iteration.
  • increment/decrement: This expression is executed at the end of each iteration. It is usually used to update the loop counter.
Example
<!DOCTYPE html>
<html>
<body>
<?php
for ($i = 0; $i < 5; $i++) {
echo "The value of i is: $i<br>";
}
?>
</body>
</html>

Try it yourself

Explanation:

  • The loop starts with $i = 0.
  • The condition ($i < 5) is evaluated before each iteration. As long as it is true, the code inside the loop is executed.
  • After each iteration, $i is incremented by 1 using $i++.
  • The loop stops when $i is no longer less than 5.



Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.