PHP For Loop and Foreach Loop

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

PHP For Loop

PHP For Loop

A for loop code should be inside of Carly brasses ( {} ) or it will end when it will get the first semicolon (;) if the semicolon is just after the for the statement it will end 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 the 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 for each loop is used to get the value from an array, so inside for each 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 for each 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 has 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.