PHP Loops: Foreach, For and While

PHP Loops are used for executing the same block again and again until the certain condition is met.

The main idea behind the loops is automating the repetitive task within a program to save the effort of the programmer as well as time. PHP supports many types of loops, some are listed below,

  • While: This loop works until the condition is true.
  • do…while: This loop executed the block of code then check the condition, if the condition is true then repeated the execution.
  • for: loops through a block until the specified condition reaches.
  • foreach: Loop through the block of code snippet and give each element of an array.
PHP Foreach, For and While Loops

Complete Explanations of PHP Loops

You will also see the example of the foreach() loop at this article, and also learn how it works with our projects.

PHP While Loop

In while loop, first, check the condition. If the given condition is true, the block of code is executed until it evaluates false. If false then the loop will be terminated.

While loop Structure

while (condition){
  //block of code to be executed;


$i = 0;
while ($i < 3){

	echo $i + 1 . "<br>";



PHP For Loop

For Loop Structure

for (variable_initialize; condition; variable_increment){
	//code to be executed



  • for…{} is the loop block
  • In variable initialization, you can initialize a variable like $i=0.
  • on the condition, is evaluated the condition for each PHP execution, if it getting true then the loop is terminated.
  • variable_increment, is used for variable initial value counter.


for($i=1; $i<=4; $i++){
    echo $i . "<br>";



PHP foreach Loop


foreach ($variable as $key => $value) {
    # code...

In foreach() loop, $variable is an array element. Loop through the block of code snippet and give each element of an array.


$UserDetails = array( 
    "name" => "PHPCODER", 
    "email" => "[email protected]", 
    "age" => 25, 
    "gender" => "male"
// Loop through UserDetails array 
foreach($UserDetails as $key => $value) { 
    echo $key . ": " . $value . "<br>"; 


email: [email protected]
age: 25
gender: male

Also Check:

PHP Loops official website where you learn more about loops in PHP,

Happy Coding..!

Was this article helpful?
My name is Bikash Kr. Panda. I own and operate PHPCODER.TECH, my native place in Odisha. I am a Web Programmer by profession and working on more than 50 projects to date. My passion is working on the web-based project using PHP and relate to all CMS and frameworks which is based on PHP.
Posts created 163

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top
mariobet - supertotobet - escort -

We are now accepting Guest Posting and creation of Backlinks
This is default text for notification bar