For Loops for Beginners – ASP, C#, PHP, JavaScript & Python Examples

A “For Loop” executes a block of code a specific number of times or while a specified condition is true.

PHP For Loop

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

php fOR lOOP PARAMETERS

  • init: Mostly used to set a counter (but can be any code to be executed once at the beginning of the loop)
  • condition: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it evaluates to FALSE, the loop ends.
  • increment: Mostly used to increment a counter (but can be any code to be executed at the end of the iteration)

Note: The init and increment parameters above can be empty or have multiple expressions (separated by commas). Example The example below defines a loop that starts with i=1. The loop will continue to run as long as the variable i is less than, or equal to 5. The variable i will increase by 1 each time the loop runs:

PHP For Loop Example Code

<?php
for ($i=1; $i<=5; $i++)
  {
  echo("The number is " . $i . "<br>");
  }
?>

Classic ASP For Loop Example Code

<%
For i = 1 to 5
 Response.Write("The number is " & i & "<br>")
Next
%>

JavaScript For Loop Example

<%
For i = 1 to 5
 Response.Write("The number is " & i & "<br>")
Next
%>

C# For Loop Example

for (int i = 0; i < 5; i++) 
      {
        Console.WriteLine(i);
      }    

Python For Loop Example

states = ["Alaska", "Alabama", "Arkansas"]
for x in states:
  print(x) 
  if x == "Alabama":
    break

Author: Rick Cable / AKA Cyber Abyss

A 16 year US Navy Veteran with 25+ years experience in various IT Roles in the US Navy, Startups and Healthcare. Founder of FinditClassifieds.com in 1997 to present and co-founder of Sports Card Collector Software startup, LK2 Software 1999-2002. For last 7 years working as a full-stack developer supporting multiple agile teams and products in a large healthcare organization. Part-time Cyber Researcher, Aspiring Hacker, Lock Picker and OSINT enthusiast.