Home » PHP Foreach Loop Implementation with Example
Php

PHP Foreach Loop Implementation with Example

Hello friends, In this tutorial we will discuss PHP Foreach Loop Implementation. Even more, we will give you some examples for better understand.

PHP Foreach Loop Implementation with Example

First of all, let’s discuss about what is foreach in PHP and how to use in a project?

The foreach loop is used to print array values alternatively. It works same like “While Loop”. But the difference is foreach works to print array values and while is used to fetch rows from MySQL database.

PHP Foreach Syntax

This is the basic syntax of foreach. $array tens for array values and $value returns the array values one by one.


foreach($array as $value)
{
   echo $value;
}

Now let’s take one example to get more idea.

Example1:


$array = array("ABC","XYZ","PQR");

foreach($array as $value)
{
   echo 'The value is '.$value;
   echo "< br />"
}

Output:


The value is ABC
The value is XYZ
The value is PQR

In above example you can see we have take one array which have values ABC,XYZ and PQR. Then we have use the PHP foreach loop to print all the array values.
echo “< br />” is used to print results in new line. As a result, you will get the result and it shows in output section above.

You can store individual values in one other array and print it manually. I will show you how it is possible in below example.

Example2:


$array = array("ABC","XYZ","PQR");

$print = array();
foreach($array as $value)
{
   $print[] = $value;
}
	
echo $print[0];
echo "< br />";

echo $print[1];
echo "< br />";

echo $print[2];

Output:


ABC
XYZ
PQR

First we have take one other array name “print” and store foreach values in this array. Then you can print this array values manually as you want. Like $print[0], $print[1] and $print[2].

$print[0] gives first value of array rather $print[1] gives second value and so on… Generally, this method is better for while loop array values. But we can use it in foreach also.

I hope you have understand the foreach loop tutorial and it will help you in live projects. Thanks for reading and if you like it please share it.

Read this article also:

About the author

John Patel

John Patel is an experienced blogger and web developer. He always likes to learn something new. He is helping the new developers through Web development and SEO(Search Engine Optimization) tutorials, tips and tricks articles.

%d bloggers like this: