Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

php
loops
web development
communitycreator

How to use for loops in PHP

NDUKWE CHIDERA K.

Let’s answer the short quiz below together.

Intro quiz

Q

Let’s meet John, an enthusiast. John wishes to blink the name of a winner on the screen in his simple number web game five times before it finally stays steady. He wishes to use a loop structure. Which one of these loops is best fitted for this scenario?

A)

A while loop

B)

A switch...case loop

C)

A do...while loop

D)

A for loop

In our simple quiz above, any option you choose might help John achieve his aims. But the right choice for John would be a for loop. You may wonder why. We will explain why that is so in this shot.

The for loop in PHP

A for loop in PHP will execute a given code block for a specified number of time. Therefore you can easily say it is a loop that is mainly used when the number of times the code will be executed is known in advance.

Now, John knows he needs the blinking name to happen five times, so he can easily use a for loop.

Basic syntax

This loop initializes the counter, sets the counter range, and finally increments the counter inside the for arguments. After this comes the code to be executed during the iteration.

for (init counter; test counter; increment counter) 
{
  //code to be executed for each iteration;
} 

Parameters

  • init counter is the start value of the counter.

  • test counter is the counter that init counter is checked against in every iteration.

  • increment provides the value with which the counter is to be incremented if it is still in the test counter range for each iteration.

Below is some simple code John could use in his program for a blinking name.

Code

In the code, we set a counter $initCounter, set a range for which the condition is valid which is $initCounter <= 5, then increment the counter by 1 ($initCounter++) in every iteration. The parser will check the $initCounter value before any iteration and if greater than 5, the loop is exited. Otherwise, it continues until it is so.

<?php 

for ($initCounter = 1;
     $initCounter <= 5; $initCounter++) {
  echo "Hurray! John Wins \n";
  echo "************** $initCounter\n";
}


?>
For loop in PHP

So, John would simply write a text blinker function and use our simple loop to execute the function over and over. This will work well for John. Thank you for aiding me to help John!

RELATED TAGS

php
loops
web development
communitycreator
RELATED COURSES

View all Courses

Keep Exploring