Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • PHP Tutorial
  • PHP Exercises
  • PHP Array
  • PHP String
  • PHP Calendar
  • PHP Filesystem
  • PHP Math
  • PHP Programs
  • PHP Array Programs
  • PHP String Programs
  • PHP Interview Questions
  • PHP GMP
  • PHP IntlChar
  • PHP Image Processing
  • PHP DsSet
  • PHP DsMap
  • PHP Formatter
  • Web Technology
Open In App
Next Article:
PHP Arrays
Next article icon

PHP Loops

Last Updated : 10 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In PHP, Loops are used to repeat a block of code multiple times based on a given condition. PHP provides several types of loops to handle different scenarios, including while loops, for loops, do...while loops, and foreach loops.

In this article, we will discuss the different types of loops in PHP, their syntax, and examples.

Types of Loops in PHP

Below are the following types of loops in PHP:

  • for loop
  • while loop
  • do-while loop
  • foreach loop

1. PHP for Loop

PHP for loop is used when you know exactly how many times you want to iterate through a block of code. It consists of three expressions:

  • Initialization: Sets the initial value of the loop variable.
  • Condition: Checks if the loop should continue.
  • Increment/Decrement: Changes the loop variable after each iteration.

Syntax

for ( Initialization; Condition; Increment/Decrement ) {
// Code to be executed
}

Example: Printing numbers from 1 to 5 using a for loop.

PHP
<?php   // Code to illustrate for loop for ($num = 1; $num <= 5; $num += 1) {     echo $num . "\n"; }   ?> 

Output
1 2 3 4 5 

2. PHP while Loop

The while loop is also an entry control loop like for loops. It first checks the condition at the start of the loop, and if it's true then it enters into the loop and executes the block of statements and goes on executing it as long as the condition holds true.

Syntax

while ( condition ) {
// Code is executed
}

Example: Printing numbers from 1 to 5.

PHP
<?php $num = 1; while ($num <= 5) {     echo $num . "\n";     $num++; } ?> 

Output
1 2 3 4 5 

3. PHP do-while Loop

The do-while loop is an exit control loop, which means, it first enters the loop, executes the statements, and then checks the condition. Therefore, a statement is executed at least once using the do...while loop. After executing once, the program is executed as long as the condition holds true.

Syntax

do {
// Code is executed
} while ( condition );

Example: Printing numbers from 1 to 5.

PHP
<?php $num = 1; do {     echo $num . "\n";     $num++; } while ($num <= 5); ?> 

Output
1 2 3 4 5 

4. PHP foreach Loop

This foreach loop is used to iterate over arrays. For every counter of loop, an array element is assigned, and the next counter is shifted to the next element. It simplifies working with arrays and objects by automatically iterating through each element.

Syntax:

foreach ( $array as $value ) {
// Code to be executed
}
or
foreach ($array as $key => $value) {
// Code to be executed
}
  • $array: The array to iterate over.
  • $value: The current value of the array element during each iteration.

Example: Iterating through an array

PHP
<?php // foreach loop over an array   $arr = array (10, 20, 30, 40, 50, 60); foreach ($arr as $val) {  	echo $val . " "; } echo "\n"; // foreach loop over an array with keys $ages = array(   	"Anjali" => 25,    	"Kriti" => 30,    	"Ayushi" => 22 ); foreach ($ages as $name => $age) {      echo $name . " => " . $age . "\n"; } ?> 

Output
10 20 30 40 50 60  Anjali => 25 Kriti => 30 Ayushi => 22 

Why Use Loops?

Loops allow you to execute a block of code multiple times without rewriting the code. This is useful when working with repetitive tasks, such as:

  • Iterating through arrays or data structures
  • Acting a specific number of times
  • Waiting for a condition to be met before proceeding

Conclusion

Loops are an important feature in PHP that help developers repeat tasks automatically. Whether you need to go through items in an array, run a block of code multiple times, or wait until a condition is true, PHP offers different types of loops to make these tasks easier and more efficient.


Next Article
PHP Arrays

C

Chinmoy Lenka
Improve
Article Tags :
  • Misc
  • Web Technologies
  • PHP
  • PHP-basics
Practice Tags :
  • Misc

Similar Reads

    PHP Tutorial
    PHP is a widely used, open-source server-side scripting language primarily designed for web development. It is embedded directly into HTML and generates dynamic content on web pages. It allows developers to handle database interactions, session management, and form handling tasks.PHP code is execute
    9 min read

    Basics

    PHP Syntax
    PHP, a powerful server-side scripting language used in web development. It’s simplicity and ease of use makes it an ideal choice for beginners and experienced developers. This article provides an overview of PHP syntax. PHP scripts can be written anywhere in the document within PHP tags along with n
    4 min read
    PHP Variables
    A variable in PHP is a container used to store data such as numbers, strings, arrays, or objects. The value stored in a variable can be changed or updated during the execution of the script.All variable names start with a dollar sign ($).Variables can store different data types, like integers, strin
    5 min read
    PHP | Functions
    A function in PHP is a self-contained block of code that performs a specific task. It can accept inputs (parameters), execute a set of statements, and optionally return a value. PHP functions allow code reusability by encapsulating a block of code to perform specific tasks.Functions can accept param
    8 min read
    PHP Loops
    In PHP, Loops are used to repeat a block of code multiple times based on a given condition. PHP provides several types of loops to handle different scenarios, including while loops, for loops, do...while loops, and foreach loops. In this article, we will discuss the different types of loops in PHP,
    4 min read

    Array

    PHP Arrays
    Arrays are one of the most important data structures in PHP. They allow you to store multiple values in a single variable. PHP arrays can hold values of different types, such as strings, numbers, or even other arrays. Understanding how to use arrays in PHP is important for working with data efficien
    5 min read
    PHP Associative Arrays
    An associative array in PHP is a special array where each item has a name or label instead of just a number. Usually, arrays use numbers to find things. For example, the first item is at position 0, the second is 1, and so on. But in an associative array, we use words or names to find things. These
    4 min read
    Multidimensional arrays in PHP
    Multi-dimensional arrays in PHP are arrays that store other arrays as their elements. Each dimension adds complexity, requiring multiple indices to access elements. Common forms include two-dimensional arrays (like tables) and three-dimensional arrays, useful for organizing complex, structured data.
    5 min read
    Sorting Arrays in PHP
    Sorting arrays is one of the most common operation in programming, and PHP provides a several functions to handle array sorting. Sorting arrays in PHP can be done by values or keys, in ascending or descending order. PHP also allows you to create custom sorting functions.Table of ContentSort Array in
    4 min read

    OOPs & Interfaces

    PHP Classes
    A class defines the structure of an object. It contains properties (variables) and methods (functions). These properties and methods define the behavior and characteristics of an object created from the class.Syntax:<?phpclass Camera { // code goes here...}?>Now, let us understand with the hel
    2 min read
    PHP | Constructors and Destructors
    In PHP, constructors and destructors are special methods that are used in object-oriented programming (OOP). They help initialize objects when they are created and clean up resources when the object is no longer needed. These methods are part of the class lifecycle.In this article, we will discuss w
    5 min read
    PHP Access Modifiers
    In object-oriented programming, access specifiers are also known as access modifiers. These specifiers control how and where the properties or methods of a class can be accessed, either from inside the class, from a subclass, or from outside the class. PHP supports three primary access specifiers: p
    4 min read
    Multiple Inheritance in PHP
    Multiple Inheritance is the property of the Object Oriented Programming languages in which child class or sub class can inherit the properties of the multiple parent classes or super classes. PHP doesn't support multiple inheritance but by using Interfaces in PHP or using Traits in PHP instead of cl
    4 min read

    MySQL Database

    PHP | MySQL Database Introduction
    What is MySQL? MySQL is an open-source relational database management system (RDBMS). It is the most popular database system used with PHP. MySQL is developed, distributed, and supported by Oracle Corporation. The data in a MySQL database are stored in tables which consists of columns and rows.MySQL
    4 min read
    PHP Database connection
    The collection of related data is called a database. XAMPP stands for cross-platform, Apache, MySQL, PHP, and Perl. It is among the simple light-weight local servers for website development. Requirements: XAMPP web server procedure: Start XAMPP server by starting Apache and MySQL. Write PHP script f
    2 min read
    PHP | MySQL ( Creating Database )
    What is a database? Database is a collection of inter-related data which helps in efficient retrieval, insertion and deletion of data from database and organizes the data in the form of tables, views, schemas, reports etc. For Example, university database organizes the data about students, faculty,
    3 min read
    PHP | MySQL ( Creating Table )
    What is a table? In relational databases, and flat file databases, a table is a set of data elements using a model of vertical columns and horizontal rows, the cell being the unit where a row and column intersect. A table has a specified number of columns, but can have any number of rows. Creating a
    3 min read

    PHP Advance

    PHP Superglobals
    PHP superglobals are predefined variables that are globally available in all scopes. They are used to handle different types of data, such as input data, server data, session data, and more. These superglobal arrays allow developers to easily work with these global data structures without the need t
    6 min read
    PHP | Regular Expressions
    Regular expressions commonly known as a regex (regexes) are a sequence of characters describing a special search pattern in the form of text string. They are basically used in programming world algorithms for matching some loosely defined patterns to achieve some relevant tasks. Some times regexes a
    12 min read
    PHP Form Handling
    Form handling is the process of collecting and processing information that users submit through HTML forms. In PHP, we use special tools called $_POST and $_GET to gather the data from the form. Which tool to use depends on how the form sends the data—either through the POST method (more secure, hid
    4 min read
    PHP File Handling
    In PHP, File handling is the process of interacting with files on the server, such as reading files, writing to a file, creating new files, or deleting existing ones. File handling is essential for applications that require the storage and retrieval of data, such as logging systems, user-generated c
    4 min read
    PHP | Uploading File
    Have you ever wondered how websites build their system of file uploading in PHP? Here we will come to know about the file uploading process. A question which you can come up with - 'Are we able to upload any kind of file with this system?'. The answer is yes, we can upload files with different types
    3 min read
    PHP Cookies
    A cookie is a small text file that is stored in the user's browser. Cookies are used to store information that can be retrieved later, making them ideal for scenarios where you need to remember user preferences, such as:User login status (keeping users logged in between sessions)Language preferences
    9 min read
    PHP | Sessions
    A session in PHP is a mechanism that allows data to be stored and accessed across multiple pages on a website. When a user visits a website, PHP creates a unique session ID for that user. This session ID is then stored as a cookie in the user's browser (by default) or passed via the URL. The session
    7 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences