Beginners Guide to PHP Part 2

By: Ryan Goose

Topics: php

Beginners Guide to PHP Part 2

Code Looping

Now that you have all of the tools needed to do storing and manipulate data, it’s time to cover how to loop through such actions. What if you wanted to loop over a set of equality and manipulation operations? Well, that is where code loops come into play.

  • The whole statement

$loopStart=0;
$loopEnd=20;

while($loopStart <= $loopEnd)
{
echo $loopStart;
$loopStart++;
}

As with all control structures, the curly brace ‘{‘ and ‘}’ are used to enclose the structure, quite similar to the use of ( ). The while statement continues to execute the code within the { } forever until the conditions within the ( ) are not true. As you’ve learned already, you know that the condition is that the variable $loopStart must be less than or equal to (<=) $loopEnd. Each time this condition is true, the statement executes the code that tells it to echo (print to screen) the value of $loopStart, then increment the same variable by 1. When $loopStart equals 20, the while statement condition executes once more, then increments the variable to 21, and the condition is never met again, so the while statement is done. You can think of while statements are, do ‘this’ while ‘that’ is true.

  • Do While

$i=0;
do
{
echo $i;
$i++;
}
while($i <= 10);

The do-while statement is just another form of the while statement. Essentially, it is saying, do this code within the { } while the statement within the ( ) is true. While there is nothing wrong with this form, it is rare to see in practice, as it is just a more verbose way of stating the same thing as a regular while() statement.

  • The Foreach
You May Also Like  Beginners Guide to PHP Part 1

$arrayVar=array(1 => ‘value1’, ‘test’ => 3 )

foreach($arrayVar as $value)
{
echo $value;
}

foreach($arrayVar as $key => $value)
{
echo $key;
echo $value;
}

The PHP ‘for each’ statement is meant to loop through array variables. The above statements will loop through the array until it reaches the end, then code execution will continue past the loop. This is the most efficient way to loop through an array especially when the array has inconsistent index values. The first statement shows how to loop through the array and just grab the index value, and the second grabs both the index (or key) and the value.

  • For Loop

for($i=0; $i <= 10; $i++)
{
echo $i;
}

The for statement is a more compact form of a while statement when looping a specific number of times. You define your iteration variable, in this case, $i, as the first argument, the conditions in the second, and the method for incrementing in the third.