PHP Loops are a type of code that can help us to run some code inside of the loop to run over and over again according to our requirement as the input, and these loops will help run the code and complete the task infinitely as we want to execute the same code inside of the loop again and again until our condition becomes false or else the code runs continuously. The word says that it will be repeated only if a certain condition is true, which is mentioned in the loop parameters to check the condition for the PHP loop/loops.
Start Your Free Software Development Course
Web development, programming languages, Software testing & others
Different Loops of PHP
Like the other programming languages, PHP offers different loop concepts. They are: WHILE LOOP, DO WHILE LOOP, FOR LOOP, FOREACH LOOP. You will get a detailed explanation of each and every loop concept of PHP below.
1. While loop
While loop will run the specific/ some block of code inside the while loop parenthesis of PHP only if the condition mentioned in the loop is true; if condition is false, the While Loop will break the code, which is in the continuous process of running the code.
Syntax:
While(Condition to check){ //Code which is need to executed or the code statements which is to run }
Explanation:
In the above syntax, a while loop is mentioned with the condition inside of the parenthesis to run statements inside of the loop only if the condition mentioned is True, or else the code inside of the loop will not run by breaking the loop get out of the loop/while loop.
Example:
The example below consists of while loop programming to print the list of numbers from 1 to 10. In the example below, variable 1 is assigned with the number 1, and then the loop program starts with the help of the $i variable value and the while loop. While loop started with the condition i
Code:
<?php $i = 1; while($i <= 10){ echo " Now The number is " . $i . "<br>"; $i=$i+1; } ?>
Output:
2. Do While Loop
The Do While loop executes the programming code inside the loop first and then checks the loop condition, while the While Loop checks the loop condition before running the code inside the loop.
Syntax:
do{ //Programming statements which is need to be executed only if the loop condition is true } While(condition to check);
Example:
The below program contains 2 do while programs to print the list of even numbers between 1-10 and the list of odd numbers between 1-10. The program also prints the sum of odd numbers, even numbers, and the sum of all the natural numbers between 1-10. The first do-while loop checks the value of the variable $i to see if it is completely divisible by the value “2”. If True, then the value will be printed, and the $k value will store the $i value; else, nothing happens, just the incrementation of the $i variable value.
Likewise, the loop continues until the $i value reaches the value “10”. Like that, others do while loop also runs by checking whether the $j value will not be divided by 2 values. If True, the $j value will be printed, and the $m will store the value. Finally, store the sum of even numbers in the variable $k and store the sum of odd numbers in the variable $l. Also, store the total sum of all natural numbers in the variable $m. Display these values in the output, as shown in the picture.
Code:
<?php $i = 1; echo "List of Even Numbers between 1-10:: "; $k = 0; $m = 0; do{ if($i%2==0){ echo " $i " ." , "; $k=$k+$i; } $m=$m+$i; $i=$i+1; }while($i <= 10); echo "<br>"." Sum of the total even numbers between 1-10 ::"." $k"; echo "<br>"; $j = 1; $l = 0; echo "List of the ODD Numbers between 1-10:: "; do{ if($j%2!=0){ echo " $j " ." , "; $l=$l+$j; } $j=$j+1; }while($j "." Sum of the total odd numbers between 1-10 ::"." $l"; echo "<br>"; echo "<br>"." Sum of the total natural numbers between 1-10 ::"." $m"; echo "<br>"; ?>
Output:
3. For loop
For loop is somewhat different when comparing the While Loop and the Do While Loop. The code will execute repeatedly if it meets a specific condition. The loop executes the code multiple times based on a specified condition.
For loop will have 3 parameters. They are initialization, condition, and the incrementation value inside the For Loop parenthesis.
Syntax:
for(initialization value; condition value; incrementing value){ //Programming code statements which is need to be executed when condition of the loop becomes TRUE }
Parameters of the For Loop:
- Initialization: In For Loop, this is the value/variable value to start the program.
- Condition: In For Loop, this is the value/variable value that must be checked. If the condition becomes true, then the program statements will run continuously by checking the condition.
- Incrementing/Incrementation: The program will increment the initial or running value of the program statements by 1 or another value as required, depending on our needs, in a For loop.
Example:
The below for loop example will print the list of the natural numbers between 1-30 and the sum of all the values between 1-30.
To begin, we set $i as 1 for the initial value. The condition is that $i should be less than or equal to 30, with an increment of $i+1. For loop will print the $i value until the i value becomes 30, and the $j variable’s value will store all the numbers/values of the $i variable and then sum them one by one in the loop until the I value reaches 30. After printing all the natural numbers using the For Loop, the sum of all natural numbers between 1-30 will be displayed.
Code:
<?php echo "List of the Natural Numbers between 1-30 :: "; $j=0; for($i=1; $i<=30; $i++){ echo "$i" . " , "; $j=$j+$i; } echo "<br>"; echo "Sum of all the natural numbers between 1-30 :: "; echo "$j"; echo "<br>"; ?>
Output:
4. Foreach Loop
PHP uses the “foreach” loop concept to iterate over arrays or multiple arrays.
Syntax:
foreach($array as $value){ //Programming code which is need to be executed }
Example:
The below example will print the values from the $colors1 variable. $colors1 variable values are the list of the colors. Using the foreach loop concept will print the colors in the array individually.
Code:
<?php $colors1 = array("Yellow", "Red", "Blue", "Green",); // Colors array accessing in the loop foreach($colors1 as $value1){ echo $value1 . "<br>"; } ?>
Output:
The above is the detailed content of PHP Loops. For more information, please follow other related articles on the PHP Chinese website!

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl


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

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

WebStorm Mac version
Useful JavaScript development tools
