Articles

Using Loops in PHP code

PHP loops Advanced Loops Lesson 12 Tutorials PHP

12. Loops in PHP lesson online free tutorial about PHP. 13. PHP Loops advanced

12. Loops in PHP

A loop is a piece of code that repeats itself until a condition is fulfilled. The loop will contiue to execute until it is told to stop.

There are several types of loops. The first one is a For loop. This will tell the processor to run the code for a many times until the condition is meet.

PHP code sample:

for($number=5;$number<10;$number++){
echo $number . " ";
}

Code output:

5 6 7 8 9

From the above example the code will begin the integer at the value of 5, increment the value by 1 while it is less than 10. As soon as $number reaches 10 it will not loop anymore.

To create a for loop enter in the start value, the end value and hwo the value is increased.

syntax $number++ is short for $number=$number+1; which will increament by 1 every loop.

Another way to do a loop in PHP is using the while statement. While only has the one condition to fill. Both are simillar.

PHP code sample:
$number=5;
while($number<10;){
echo $number . " ";
$number++;
}

Code output:

5 6 7 8 9

Using WHILE for looping can create the same output as the for loop but requires more lines of code. It would essentially be breaking apart the different components of the FOR loop statement. The concept is the same that if the condition comes back false it will contiue to perform the loop code.

13. PHP Loops advanced

The FOREACH loop can pull array data and neatly place both the key and value in easy output formats. FOREACH will loop until each item has been raeched. As we learned in the previous lessons arrays have keys and values attached to each key. If you wanted to loop within an array that just had numeric values the key would be the number coinciding with the array.

$myArray = array("A","B","C","D");

foreach( $myArray as $key => $value){
  	echo "KEY : $key, VALUE : $value <br />"; 
 }