PHP For Loop and Foreach Loop

The php for loop and Foreach both loop is used for execute a portion of code several time, the php for loop is mainly used for execute a branch of code with counter with increment or decrements by a particular integer value and Foreach loop is used for get values from array and work with that.

PHP For Loop

PHP For Loop

A for loop code should be inside of Carly brasses ( {} ) or it will ended when it will get the first semi colon (;) if the semicolon is just after the for statement it will ended there.

The for loop starts with initiate with a value then its check if its condition is true or not then execute the code inside true if the condition is true,

and then the counter of loop will increment or detriment and then will check the condition again if return true it will go inside the loop. and the loop will end when the condition will return false after the value increment or decrements.

example:


<?php
for ($i=0; $i <5 ; $i++)
echo $i; // the php for loop will print 0 1 2 3 4
echo $i; // it will print 5 as after increment the condition of for loop returns false.

for ($i=0; $i <5 ; $i++) ; // the loop is ending here
echo $i; // it will print 5 as after increment the condition of for loop returns false.

for ($i=0; $i < 5; $i++) {
echo $i; // the php for loop will print 0 1 2 3 4
}
echo $i; // it will print 5 as after increment the condition of for loop returns false.
?>

PHP Foreach Loop

PHP Foreach Loop

PHP Foreach Loop

As i have already told that a foreach loop is used to get the value from an array, so inside foreach the first statement is from where to get the values , then the key or id or index of the array and then the value of the array for the particular array index, and the key and value will fetch from one by one while the foreach loop will run.

Example:


<?php
$variable = array('color' => 'Blue', 'area' => '350cm', 'cost' => '$100' );

foreach ($variable as $key => $value) {
echo $key . ' => ' . $value . '<br/>';
}

// The loop will print
// color => Blue
// area => 350cm
// cost => $100
?>

Please try the PHP For Loop and Foreach Loop and I hope that the post have given a clear view on PHP For Loop and Foreach Loop.

Thanks for reading.

Share The Post On -

Add a Comment

Your email address will not be published. Required fields are marked *

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