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:
<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:
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:
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:
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!

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

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

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.

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

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.

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

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.

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


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

Atom editor mac version download
The most popular open source editor

SublimeText3 Linux new version
SublimeText3 Linux latest version

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
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
Recommended: Win version, supports code prompts!
