Tuesday, January 26, 2016

FOR LOOP IN PHP: Display Numbers Using For Loop in PHP

PHP loops execute a block of code a specified number of times. There are four (4) types of loops in PHP. The for loop, foreach loop, do while loop and the while loop. In this tutorial, we will be focusing on the while loop which I often used in creating iterations to save code and memory space.

For loop is used if you already know how many times your code will be executed.

Syntax for loop
init - initialization of your variable/counter
condition - test whether the statement is false to be able to continue execution. If true, then the loop stops.
increment/decrement - adds/subtracts a certain value

Let's say you want to display numbers from 1 to 10 using a for loop. The following is the code.

PHP Code For Loop
for ($i=1;$i<=10;$i++)
echo $i;
echo "<br>";

I will explain each line of the above code. $i will serve as your loop counter, $i<=10 is your condition and $i++ is your increment. In every iteration, the condition will be checked and will return a boolean value which is either a true or false value. Once true, it will execute the code inside the loop, otherwise, it will terminate the loop. Increment is important in a loop, without it, your browser will surely crash since you created an infinite loop.

Output For Loop

That would be all. Thank you for visiting and hope this helps you. Feel free to leave a comment below for any questions. I got some other articles related to php in blog and even related to loops.

FOR LOOP IN PHP: Display Numbers Using For Loop in PHP

No comments:

Post a Comment