UberPages :: Tutorials :: PHP Tutorials :: PHP Loop Structures

Quick Menu

Being able to use any programming language, you need to have reaction to input. With PHP for instance, there are many ways to automate actions. Here are some of the control or loop structures available in PHP.


If Else

This can be very basic, widely used, and you will see it often.

<?php

$strVar = "Hello";

if ($strVar == "Hello") {
     echo "Your variable contains the word, Hello!";
} else {
     echo "Please try again.";
}

?>

As you can see, it's pretty basic, but it is very essential. Also note, that when using this control structure, you don't always need the ELSE instructions. If you see it more useful to use a bunch of IF statements, then go right ahead. Your code might just not be as nice. :)


While Loop

The While Loop will do whatever you tell it to WHILE something is true, plain and simple.

<?php

$number = 1;

while ($number < 10)

{
     echo $number . '<br>';
     $number += 1;

}

?>

As you can see, the script starts out by setting the variable called number to 1, then it starts the looping. In this case a while loop and to be more specific, while the variable is less than 10, it will do whatever is in its loop structure.

Here, we print out the number to the browser, then add one to the variable, then restart the loop, Just be sure to increment the control number in the loop so it doesn't loop forever.

... Unless you do something like this:

<?php

$number = 1;

while ($number < 10)

{
     echo $number . '<br>';
     $number += 1;

   if ($number == 6)
   {
      break;
   }

}

?>

For the purpose of this test the newly added BREAK command was added in an IF condition, but the break command can be used at any point, it's just up to how you use it. Once the code runs into the break command, it jumps out of that loop and continues along it's way.


For

The For loop is pretty much like an until loop in other languages. Take a look at the loop:

<?php

for ($number = 1; $number <= 10; $number++) {
   echo $number . '<br>';
}

?>

This might look a bit cryptic at first, but it's pretty straight forward since everything about the loop is controlled in the first line.

So the first statement initializes the number, in this case, to one.

Then it set's the parameter to which the loop will continue to run at, in this case, as long as the number is below or equal to ten.

Last, it sets the increment for the variable every time the loop cycles through once, in this case, it adds one to the variable named number.

That all being said, this loops through until its variable hits ten, all the while printing it out on the browser screen. This is pretty basic, but, the method shouldn't be complex, the application should be. Get crackin'.










Affiliates and Uber Linkage