When we need to run some specific code in a fixed limit then we use loops in php e.g. We have 1000 records of students save in the database now we get all data in array and then we run loop and bound this loop by counting total number of records. Now we get record array one by one and print our required data like listing all records.
Let's make a simple html table with "for" loop to understand more loops in php. Running a loop, we need three main points.
- variable value starting point
- variable stopping limit
- variable increment value
for($i=0; $i<20; $i++){
// code block
}
If you check the first line i would have considered $i as variable and it's starting value is 0 and it will run till it reaches 19 so 0-19 means it runs 20 times because we give the condition it will run less than 20. Before running loop let check the html table code so that we understnad loop structure well.
<table border='1'>
<tr>
<td> column 1 </td>
<td> column 2 </td>
<td> column 3 </td>
</tr>
</table>
i draw a table having only one row with three columns. Now using loops in php i want to create a table with 20 rows so actually we need to apply loop on row. Let's see php code with print command.
<?php
echo("<table border='1'>");
for($i=0; $i<20; $i++){
echo("<tr>");
echo("<td> column 1 </td>");
echo("<td> column 2 </td>");
echo("<td> column 3 </td>");
echo("</tr>");
}
echo("</table>");
?>
so printing table staring and closing tags are out of loop as we need only one time to print these tags but we need to run row with td tags in loop so we put only these in loop and when we run this code a table with created with 20 rows. Now we can run as many rows as we need, we just need to change the condition i.e. $1< 200 now 200 rows will create.
Let see one more example we want to print count table for kids learning using loops in php.
<?php
for($x=1; $x<11; $x++){
$table_var=7;
$total= $x * $table_var;
echo($table_var. " * ". $x . " = " . $total);
}
Now we are also using loop variable to help printing table and by changing value of $table_var we can print any table if you run this code, you will get output like below.
7 * 1 = 7
7 * 2 = 14
.....
.....
it will go till
7 * 10 = 70
so, loop will start from 1 and less than 11 means 10 will ending point.
Hope you will get some idea about loops in php.
Thanks