search

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 Tests

Start 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.

While Loop in PHP

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:

  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 a while loop in PHP:

Example #1

Printing the value of a field according to the specific condition.

Code:



<title>PHP while Loop Example 1</title>


<?PHP $value = 10;
while ((int)$value > 5) {
echo "The value of the field is : $value <br>";
$value--;
}
?>

Output: 

While Loop in PHP

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:



<title>PHP while Loop Example 2</title>


<?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";
?>

Output: 

While Loop in PHP

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:



<title>PHP while Loop Example 2</title>


<?PHP $table_number= 6;
$mult =1;
while((int)$mult<=10)
{
echo "$table_number * $mult";
echo "<br>";
$mult++;
}
?>

Output:

While Loop in PHP

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

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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Optimize PHP Code: Reducing Memory Usage & Execution TimeOptimize PHP Code: Reducing Memory Usage & Execution TimeMay 10, 2025 am 12:04 AM

TooptimizePHPcodeforreducedmemoryusageandexecutiontime,followthesesteps:1)Usereferencesinsteadofcopyinglargedatastructurestoreducememoryconsumption.2)LeveragePHP'sbuilt-infunctionslikearray_mapforfasterexecution.3)Implementcachingmechanisms,suchasAPC

PHP Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!