Difference between for and foreach loop in php
These two loops are mainly used when you will work with array in php. You have worked with for and foreach loop in PHP, but do you know the difference between these two? Here they are described below:
for()
for() loop is used when you know the number of times you have to loop. It means you know the loop termination counter in advance. Here is the Syntax of for loop
Syntax:
for (init counter; test counter; increment counter)
{
code to be executed;
}
{
code to be executed;
}
Example:
<?php
for ($x = 0; $x <= 5; $x++)
{
echo "The number is: $x <br>";
}
?>
for ($x = 0; $x <= 5; $x++)
{
echo "The number is: $x <br>";
}
?>
Output
0
1
2
3
4
5
0
1
2
3
4
5
foreach()
foreach() works only with the array. It is used when you have loop through the entire array. In this loop you do not need to specify the length of the array, array counter will automatically incremented to 1 after each element traversal.
foreach used with the associative array where you don't know the index of the array. In associative array elements are stored in the key/value pair when key can be any value either text or numeric.
Syntax:
code to be executed;
}
Example:
<?php
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $value) {
echo "$value <br>";
}
?>
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $value) {
echo "$value <br>";
}
?>
output:
red
green
blue
yellow
foreach with associative array()
Associative array in which elements are stored in the form of key/pair value.
It is not like simple array where values are stores in the numerical indexs. In associative array you can store values in any type of index either numeric or text.
foreach() loop play vital role where key/index is a text value.
Here is the example demonstrate this
Associative array in which elements are stored in the form of key/pair value.
It is not like simple array where values are stores in the numerical indexs. In associative array you can store values in any type of index either numeric or text.
foreach() loop play vital role where key/index is a text value.
Here is the example demonstrate this
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
foreach($age as $x => $x_value) {
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
foreach($age as $x => $x_value) {
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>
Output
Key= Peter, Value= 35
Key= Ben, Value=37
Key=Joe, Value=43
You can see in the above you can see that foreach loop itself walk through the entire array without increment counter. Pointer will automatically point to next element after each iteration.
No comments:
Post a Comment