Accessing Values of Multi-Dimensional Arrays in PHP


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:

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:

Accessing Two Dimensional Array with Two ForEach Loops

For this we have to use two for each loops nested inside one another.

Example:

Accessing Three Dimensional Array with Two ForEach Loops

When array levels go deep, more and more for each loops are required.

Example:

This can go on and on for as many levels as you want.

You may also like

Comments are closed here.

Advertisements

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 2 other subscribers