How to Loop Through a Multidimensional Array in PHP 


               


How to Loop Through a Multidimensional Array in PHP



PHP




In this article, we show how to loop completely through a multidimensional array in PHP.

A multidimensional array is an array that contains arrays.

So let's say we have created the following multidimensional array below composed of people: their name, email, city, and state. The second block of PHP shows how to access all of the data in the array.



So this is how we can loop through a multidimensional array in PHP.

The first foreach() loop obtains each array within the array.

The entire array is called $people. The $person variable represents each array within the $people array.

We then use another foreach() loop. This time we take the individual array within the parent array and we loop through all the key-value pairs of the array. All the key-value pairs represent the name, email, city, and state values of each person.

We echo out these key-value pairs.

We create a variable called $num and initially it is set equal to 0. However, in the first foreach() loop, it is incremented by 1. This is so we can numerically each track of each new record. We echo out this number for each array that the foreach loop encounters in the multidimensional array.

Because multidimensional arrays are basically arrays nested inside other arrays, all we have to do to loop through them is use nested loops.

Running the above PHP code, we get the following output below.

Actual PHP Output



# 1
name: Jennifer Kimbers
email: abc@gmail.com
city: Seattle
state: Washington

# 2
name: Rodney Hutchers
email: def@gmail.com
city: Los Angeles
state: California

# 3
name: Robert Smith
email: ghi@gmail.com
city: Michigan
state: Missouri






Related Resources



How to Access the Elements of a Multidimensional Array in PHP

HTML Comment Box is loading comments...