PHP For Loops

The For Loop is more complex than Do-While and While loops, and it is also more powerful. The For Loop is very useful if you want to display a list of numbers or something else repeatedly.

Syntax

for (variable; condition; increment/decrement) {

echo 'code to execute';

}

Now let's print out numbers 1 - 75:

Sponsored Links
for ($num=1; $num<75; $num++){

echo $num.'<br>';

}

Here in the first line we declared the variable num and set the value to 1, and then said if num is less than 75 increment it. In the second line we print out the results all on a separate line. This can be very useful, especially for filling out online forms (ex: drop-down lists). The general HTML code for displaying a drop-down list is:

<form method="post">

    <select name="Select1" style="width: 209px">

    <option>1</option>

        <option>2</option>

            <option>3</option>

    </select></form>

Instead of writing <option>x</option> 75 times, we can do it the easy way with PHP. The code is the same as above, we just need to add the HTML parts and concatenate.

<select>

<?php

for ($num=1; $num<75; $num++){

    echo '<option>' .$num. '</option>';
}

?>

</select>

We use the <select> tag around the PHP open and closing tags since we want the code to be in a drop-down list, and then we echo it out.

Try It!

Choose a number between 2-2000: 

Foreach Loops

Similar to the For Loop, the Foreach Loop is used to loop over arrays.

Syntax

foreach ($arrayname as $localvariable)
{
...code.
}

Example

<?php

$games = array('GTA4', 'SWAT4', 'BF3', 'MW3', 'GRID');

foreach ($games as $value){
    echo '<br>'.$value.'<br>';
}

?>

Code Explained

  • First, make an array called 'games' (to learn about arrays see the array tutorial)
  • Use the Foreach statement and loop through the arrays
  • Echo each value out on a new line

Output

  • GTA4
  • SWAT4
  • BF3
  • MW3
  • GRID

If desired, you can also put the arrays in a drop-down list like this:

<select>
<?php

$games = array('GTA4', 'SWAT4', 'BF3', 'MW3', 'GRID');

foreach ($games as $value){
    echo '<option>'.$value.'</option>';
}
?>
</select>

This is the same process as before, but the array will be printed out in a drop-down list.