There are several ways to access values of arrays in PHP. Since, arrays can go multi-level or multi-dimensional, it can be confusing to access the exact key and its value. But thankfully there is “for each loop” in php which will allows us to loop through an array and get to the exact key and value.
Finding the Array Length and Looping Through it
This method only works for indexed arrays because we use numbers to access the values.
Example:
<?php $names = array ("Ashish","Michael","Robert","Chris"); $length = count($names); for($key=0;$key<$length;$key++) { echo $names[$key]."<br />"; } ?>
Output: Ashish Michael Robert Chris
Using ForEach to Loop Through Associative Array
This method is used to cycle through all the keys and values of an associative array. ForEach statement continues the loop as long as there are keys and values remaining in an array.
Example:
<?php $names = array ( "Ashish"=>"Kathmandu", "Michael"=>"New York", "Chris"=>"Australia" ); foreach($names as $key => $value) { echo $key ." ". $value; echo "<br />"; } ?>
Output: Ashish Kathmandu Michael New York Chris Australia
Accessing Two Dimensional Array with Two ForEach Loops
For this we have to use two for each loops nested inside one another.
Example:
<?php $names = array( "one"=>array("Ashish",27), "two"=>array("Michael",20), "three"=>array("Chris",35), ); foreach($names as $key => $value) { foreach($value as $newkey=>$newvalue){ echo $newkey." = ".$newvalue,"<br />"; } } ?>
Output: one = Ashish one = 27 two = Michael two = 20 three = Chris three = 35
Accessing Three Dimensional Array with Two ForEach Loops
When array levels go deep, more and more for each loops are required.
Example:
<?php $names = array( "Level1"=>array( "Level2"=>array( "Level3"=>"Ashish" ) ) ); foreach($names as $key => $value) { foreach($value as $newkey=>$newvalue){ foreach($newvalue as $newerkey=>$newervalue) { echo $key." - ".$newkey." - ".$newerkey." - ".$newervalue; } } } ?>
Output: Level1 - Level2 - Level3 - Ashish
This can go on and on for as many levels as you want.