Thursday , April 25 2024
Home / Core PHP / PHP 5 for Loops

PHP 5 for Loops

PHP for loops execute a block of code a specified number of times.

The PHP for Loop
The for loop is used when you know in advance how many times the script should run.

Syntax

for (init counter; test counter; increment counter) {
code to be executed;
}
Parameters:

init counter: Initialize the loop counter value
test counter: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it evaluates to FALSE, the loop ends.
increment counter: Increases the loop counter value
The example below displays the numbers from 0 to 10:

Example

Select Code
<?php 
for ($x=0; $x<=10; $x++) {
  echo "The number is: $x <br>";
} 
?>

The PHP foreach Loop
The foreach loop works only on arrays, and is used to loop through each key/value pair in an array.

Syntax

foreach ($array as $value) {
code to be executed;
}
For every loop iteration, the value of the current array element is assigned to $value and the array pointer is moved by one, until it reaches the last array element.

The following example demonstrates a loop that will output the values of the given array ($colors):

Example

Select Code
<?php 
$colors = array("red","green","blue","yellow"); 

foreach ($colors as $value) {
  echo "$value <br>";
}
?>

About v.shakya

I am V.Shakya, Software Developer & Consultant I like to share my ideas, views and knowledge to all of you who come across my website. I am young, enthusiastic, highly motivated and self disciplined person. I completed my studies in Master of Computer Application and currently giving my technical expertise to one of the Big IT company. I have more than fifteen years of experience in vast field of Programming , Designing and Development of websites and various software's.

Check Also

PHP 5 Arrays

An array stores multiple values in one single variable: Example <?php $cars=array("Volvo","BMW","Toyota"); echo "I like …

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.