EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login

While Loop in PHP

Home » Software Development » Software Development Tutorials » PHP Tutorial » While Loop in PHP

While Loop in PHP

Introduction to While Loop in PHP

As we all know that PHP is one of the most widely used languages for web development. In any programming language, understanding the basic concepts is very important before diving deep in the advanced ones. Loops are one of the largely and most commonly used while writing any piece of code as their main purpose is to execute the same piece of code repeatedly according to specific requirements of a programmer. Code/statements inside the while loop in PHP execute until the condition specified by the programmer remains ‘true’. There is no need to specify the exact number of iterations for which a while loop should run unlike ‘for’ loops.

Below mentioned is the syntax of while loop in PHP:

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Syntax:

while (condition to be true)
{
..
..
// Set of Statements to be executed
..
..
..
}

Statements inside the while loop will not execute once the condition mentioned in the loop is evaluated to be false.

Flowchart:

Below given is the basic flowchart expressing the process of how the while loop performs its action.

While Loop in PHP flow chart

How While Loop works in PHP?

As explained above, while loop works until the condition specified is satisfied. Working of while loop in PHP is explained in the below steps:

Popular Course in this category
PHP Training (5 Courses, 3 Project)5 Online Courses | 3 Hands-on Project | 28+ Hours | Verifiable Certificate of Completion | Lifetime Access
4.5 (5,731 ratings)
Course Price

View Course

Related Courses
Java Servlet Training (6 Courses, 12 Projects)All in One Software Development Bundle (600+ Courses, 50+ projects)
  1. First the condition given inside the brackets after the while keyword is checked.
  2. If the condition is satisfied or is true, then the control is moved inside the loop.
  3. The statements inside the loop are executed.
  4. Once all the statements inside the loop are executed, the condition is checked again and if it is true the execution continues.
  5. When the condition is evaluated to be false, the control will not move inside the loop and the while loop terminates.

Examples of While Loop in PHP

Below are the different examples of while loop in PHP:

Example #1 – Printing the value of a field according to the specific condition.

Code:

<!DOCTYPE html>
<html>
<head>
<title>PHP while Loop Example 1</title>
</head>
<body>
<?PHP
$value = 10;
while ((int)$value > 5) {
echo "The value of the field is : $value <br>";
$value--;
}
?>
</body>
</html>

Output: 

The value of the field is 10
The value of the field is 9
The value of the field is 8
The value of the field is 7
The value of the field is 6

Explanation

In the above program, variable with the name ‘value’ is assigned with the value 10. Now the while loop condition is checked, i.e. 10 > 5, which is true so the statements inside the loop will execute. The value of variable ‘value’ is decreased by 1 and again checked with the while condition. Execution of statements inside the while loop continues until the value of the variable becomes 6. Once the value becomes 5 and the condition evaluates to be false (5 > 5), the while loop terminates and the echo statement inside the while loop will not execute.

Example #2 – Printing the sum of digits of a given number.

Code:

<!DOCTYPE html>
<html>
<head>
<title>PHP while Loop Example 2</title>
</head>
<body>
<?PHP
$number = 107;
$sum=0; $rem=0;
while((int)$number != 0)
{
$rem=$number%10;
$sum = $sum + $rem;
$number=$number/10;
}
echo "The Sum of digits of number given 107 is $sum";
?>
</body>
</html>

Output: 

The Sum of digits of the number given 107 is 8

Explanation

In the above example, the sum of the digits of a number ‘107’ is calculated which is 1+0+7. First the condition of while loop, i.e. 107 != 0, is checked. As the condition evaluates to be true, control will move inside the loop remainder (rem) is calculated (107%10) i.e. 7 and is added to the sum variable, which becomes 0+7 =7. Number now becomes 107/10 = 10. Again the number 10 is checked against the while condition which is set to be true and the control will again move inside the loop. Rem variable now is 10%10 =0 and sum becomes 7+ 0 = 7 . number variable now becomes 10/10 =1, which is again not equal to 0 and move inside the while loop, so rem variable becomes 1%10 =1. sum =7+1 =8. Number variable becomes 1/10 =0. Now the while condition is evaluated to be false so the cursor will not move inside the while loop and the sum final value becomes 8 which is printed on the screen.

Example #3 – Generate and print the table of number 6.

Code:

<!DOCTYPE html>
<html>
<head>
<title>PHP while Loop Example 2</title>
</head>
<body>
<?PHP
$table_number= 6;
$mult =1;
while((int)$mult<=10)
{
echo "$table_number * $mult <br>";
$mult++;
}
?>
</body>
</html>

Output:

6
12
18
24
30
36
42
48
54
60

Explanation

In the above program, the table of the variable, ‘table_number’ is printed. In general, a number whose table needs to be printed remains the same, i.e. 6 in this case whereas the multiples keep on incrementing from 1 till 10. For the first time when the value of the ‘mult’ variable is 1, so the condition of while loop, i.e. 1<=10 sets to be true and the cursor will move inside the loop and the value of 6 * 1= 6 is printed on the screen. The value of the ‘mult’ variable is incremented by 1, i.e. now mult =2. Again the condition of the while loop, i.e. 2 <=10 is checked and the multiplication table of 6 is printed until the ‘mult’ variable is less than equal to 10. Once the value of the ‘mult’ variable becomes 11, the cursor will not move inside the loop and the execution of loop terminates.

Conclusion

The above explanation clearly describes the syntax of a while loop along with its working in a program. Though there are 4 types of loops used in PHP and every loop is used in a particular situation. While loop is mainly used by the programmer when the iterations are not fixed and we need to execute the set of statements until the main condition evaluates to be true. It is important to understand the working of loops before using them as partial knowledge of them can sometimes lead to unexpected results.

Recommended Articles

This is a guide to while loop in PHP. Here we discuss how while loop works in PHP, syntax, flowchart along with different examples and code implementation. You may also look at the following articles to learn more-

  1. What is PHP?
  2. PHP Compiler
  3. Palindrome in PHP
  4. PHP Commands

PHP Training (5 Courses, 3 Project)

5 Online Courses

3 Hands-on Project

28+ Hours

Verifiable Certificate of Completion

Lifetime Access

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
PHP Tutorial
  • Loops
    • PHP Loops
    • For Loop in PHP
    • PHP Do While Loop
    • PHP While Loop
    • While Loop in PHP
    • Foreach Loop in PHP
  • PHP Basic
    • Introduction To PHP
    • What is PHP
    • PHP Keywords
    • Advantages of PHP
    • Career In PHP
    • Comments in PHP
    • PHP Commands
    • PHP Frameworks
    • PHP Compiler
    • Variables in PHP
    • PHP Superglobal Variables
    • PHP Versions
    • Object in PHP
    • What is Drupal
    • Top PHP Frameworks
    • WebStorm IDE
    • What is phpMyAdmin?
    • PhpStorm
    • Install phpMyAdmin
    • Phalcon Model
  • Data Types
    • PHP Data Types
    • PHP Integer
    • PHP Booleans
  • Operators
    • PHP Operators
    • Arithmetic Operators in PHP
    • Comparison Operators in PHP
    • Logical Operators in PHP
    • Bitwise Operators in PHP
    • Ternary Operator in PHP
    • PHP String Operators
  • Control Statements
    • Control Statement in PHP
    • PHP if Statement
    • if else Statement in PHP
    • elseif in PHP
    • PHP Switch Statement
    • Continue in PHP
    • Break in PHP
  • Constructor
    • Constructor in PHP
    • Destructor in PHP
  • State Management
    • Cookie in PHP
    • Sessions in PHP
  • Array
    • What is PHP Array
    • Arrays in PHP
    • 2D Arrays in PHP
    • Associative Array in PHP 
    • Multidimensional Array in PHP
    • Indexed Array in PHP
    • PHP Array Functions
    • PHP unset Array
    • PHP Append Array
    • PHP Array Search
    • PHP Split Array
    • PHP array_push()
    • PHP array_pop()
  • Functions
    • Functions in PHP
    • PHP Math Functions
    • PHP Recursive Function
    • PHP String Functions
    • Hashing Function in PHP
    • Date Function in PHP
    • PHP Anonymous Function
    • Calendar in PHP
    • PHP Call Function
    • PHP Pass by Reference
    • PHP ucfirst()
    • PHP ucwords()
    • trim() in PHP
    • isset() Function in PHP
    • PHP replace
    • PHP fpm
    • PHP strpos
    • preg_match in PHP
    • PHP preg_replace()
    • PHP ob_start()
    • PHP Reflection
    • PHP Split String
    • PHP URL
    • PHP preg_match_all
    • PHP strtoupper()
    • PHP preg_split()
    • PHP substr_replace()
    • PHP setlocale()
    • PHP substr_count()
    • PHP Serialize
    • PHP strlen()
    • PHP async
    • PHP Date Time Functions
    • PHP timezone
    • PHP Data Object
    • print_r() in PHP
    • PHP header()
    • PHP strip_tags()
    • PHP chop()
    • PHP MD5()
    • PHP unset()
    • PHP crypt()
    • PHP wordwrap()
    • PHP is_null()
    • PHP strtok()
    • PHP bin2hex()
    • PHP parse_str()
    • PHP levenshtein()
    • PHP addslashes()
    • PHP strtotime
    • PHP sha1()
    • PHP explode()
    • PHP sscanf()
    • PHP require_once
    • PHP Zip Files
    • PHP $_SERVER
    • PHP $_POST
    • PHP Include and Require
    • PHP POST Method
  • Advanced
    • Overloading in PHP
    • Overriding in PHP
    • Method Overloading in PHP
    • Inheritance in PHP
    • Multiple Inheritance in PHP
    • PHP Interface
    • Encapsulation in PHP
    • PHP Constants
    • PHP Magic Constants
    • PHP Regular Expressions
    • PHP GET Method
    • PHP Annotations
    • PHP Encryption
    • PHP file Functions
    • PHP readfile
    • PHP?Write File
    • PHP Append File
    • PHP Type Hinting
    • PHP Filters
    • PHP Float
    • PHP Form
    • PHP Form Validation
    • Sorting in PHP
    • PHP usort()
    • PHP Stack Trace
    • PHP Stack Overflow
    • PHP Pagination
    • PHP implode
    • Polymorphism in PHP
    • Abstract Class in PHP
    • PHP Final Class
    • PHP Custom Exception
    • error_reporting() in PHP
    • PHP Log Errors
    • Access Modifiers in PHP
    • PHP Change Date Format
    • Static Method in PHP
    • PHP File Handling
    • PHP Output Buffering
    • Get IP Address in PHP
    • Upload a File in PHP
    • String in PHP
    • Public Function in PHP
    • Private in PHP
    • Protected in PHP
    • basename in PHP
    • Validation in PHP
    • PHP mail()
    • PHP Email Form
    • PHP Directory
    • PHP Create Session
    • PHP include_once
    • PHP json_decode
    • PHP XMLWriter
    • PHP XML Reader
    • PHP XML Parser
    • PHP XML into Array
    • Phalcon Framework
  • Programs
    • Patterns in PHP
    • Star Patterns in PHP
    • Swapping in PHP
    • Fibonacci Series PHP
    • Factorial in PHP
    • Reverse String in PHP
    • Square Root in PHP
    • Random Number Generator in PHP
    • Palindrome in PHP
    • Prime Numbers in PHP
    • Armstrong Number in PHP
    • Socket Programming in PHP
    • Login Page in PHP
    • PHP Login Template
    • PHP Object to String
  • Database
    • PHP Database Connection
    • How to Connect Database to PHP
  • Interview Questions
    • PHP Interview Questions
    • PHP OOP Interview Questions
    • CakePHP Interview Questions
    • Core PHP Interview Questions

Related Courses

PHP Training Course

Java Servlet Training

Software Development Course Training

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

Special Offer - PHP Training (5 Courses, 3 Project) Learn More