Monday, January 25, 2016

FOREACH LOOP PHP: Display Data from An Array Using Foreach Loop in PHP

Today, we will be dealing with the used of an array that is somewhat similar with your variable. A variable can hold or store a single value while an array stores multiple values at the same type. An array is a special variable that stores not just a single value, but multiple values of a single type. I will discuss how arrays works and will provide an example for you to understand it well.

Let's say we have an array of names such as Reah, Riza, Mond and Kris. They are all first names of persons. Usually, a variable can only hold one (1) value at a time. But with arrays, you can store multiple values at the same time. So if we want to store those first name in just a single container, then we will be using an array.

You can access the values in array using two (2) ways. First is by accessing the value using the assigned index. By default, array index starts with zero (0). If the given array value is Reah, Riza, Mond, Kris, then Reah is in index 0, Riza is 1, Mond is 2, and Kris is 3. You can try the code below by pasting it to a text editor and save it with .php file extension.

PHP Code Array

echo $name[0];
echo "<br>";
echo $name[1];
echo "<br>";
echo $name[2];
echo "<br>";
echo $name[3];

And second way in accessing values in an array is with the use of a foreach loop. Each value will be stored in the variable $value and will be displayed. The loop will continue as long as there are still values in array.

foreach ($name as $value)
echo $value;
echo "<br>";

Output Array

That would be all. Thank you for visiting and hope this helps you. Feel free to leave a comment below for any questions. I got some other articles related to php in blog and even related to loops.

FOREACH LOOP PHP: Display Data from An Array Using Foreach Loop in PHP

No comments:

Post a Comment