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
<?php
$name=["Reah","Riza","Mond","Kris"];
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.
No comments:
Post a Comment