While Loop in PHP
As we all know that PHP is one of the most widely used languages for web development. Understanding the basic concepts is very important in any programming language before diving deep into 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 programmer’s condition remains ‘true’. There is no need to specify the exact number of iterations for which a while loop should run, unlike ‘for’ loops.
ADVERTISEMENT Popular Course in this category PHP DEVELOPER - Specialization | 8 Course Series | 3 Mock TestsStart Your Free Software Development Course
Web development, programming languages, Software testing & others
Below mentioned is the syntax of while loop in PHP:
Syntax:
while (condition to be true) { .. .. // Set of Statements to be executed .. .. .. }
Statements inside the while loop will not execute once the loop’s condition is evaluated to be false.
Flowchart
Below given is the basic flowchart expressing the process of how the while loop performs its action.
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:
- First, the condition given inside the brackets after the while keyword is checked.
- If the condition is satisfied or is true, then the control is moved inside the loop.
- The statements inside the loop are executed.
- Once all the statements inside the loop are executed, the condition is checked again, and if it is true, the execution continues.
- 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 a 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:
Explanation
In the above program, a 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:
Explanation
In the above example, the sum of the digits of the 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 the 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"; echo "<br>"; $mult++; } ?> </body> </html>
Output:
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 while loop condition, 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 the 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. The programmer mainly uses a loop when the iterations are not fixed, and we need to execute the set of statements until the main condition is evaluated. It is important to understand the working of loops before using them, as partial knowledge of them can sometimes lead to unexpected results.
The above is the detailed content of While Loop in PHP. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7
