How to use foreach in PHP

2

Foreach is one of the very commonly used codes in PHP.  In web development we usually work on database a lot and we need to create array a lot on online processing. So it is quite normal that a lot of array will generate in this process and when we have to process this data we have to take information one by one and put that into a proper manner. This code helps us to do this work in a easier way.

Here let me tell you how foreach works. Foreach is a pseudo code of PHP program. This pseudo code can take information one by one from an array. Suppose we  have an array consisting 10 items in it and we need to compare the information using either key or value of every single item from that array. We can do that in different ways like using for loop or while loop. But only in PHP it gives us this pseudo code to do whole coding in one single code.

If we go through a simple example then we can start understanding the issue.

$vehicles = array(“Car”, “Bike”, “Truck”, “Boat”);

foreach ($vehicles as $value) {
echo “$value <br>”;
}

The result of the above script is

Car

Bike

Truck

Boat

Now as we can see that it deconstructs the array and brings every single element as an individual variable value.

If we want to do this same thing using for loop than we have to go through a little bit more work than this. The for loop would look like below.

<?php

$vehicles = array(“Car”, “Bike”, “Truck”, “Boat”);
for ($x = 0; $x <= 3; $x++) {

$c= $vehicles[$x];
echo ” $c <br>”;
}
?>

We will get the same result from this above code.

By comparing above two scripts we can easily see that the first script is much easier than the second one.

If we have a multidimensional array, we have to use more than one foreach loop. We need to have a little bit more calculation to clear that up. If we take closes look to a multidimensional array than we can understand this very easily.

Suppose we have a multidimensional array like below.

$mularray =array (

array (“a”,”b”, ”c”),

array (”ab”,”bc”,”cd”)

);

foreach ($mularray as $singarray) {
$c = $singarray;

foreach ($singarray as $values) {
$c = values;

echo “$c”;

}

}

That’s way we can easily find the values from multidimensional array.

2 Comments
  1. Zuber says

    Good Keep it up Dear

    1. admin says

      Thank you.

Leave A Reply

Your email address will not be published.