This post will discuss how to iterate over an associative array in PHP.

1. Using foreach construct

A simple solution to looping through an associative array is using the foreach loop. It has two syntaxes:

1. The first syntax traverses the given array, and on each iteration, it assigns the key of the current element to the $key variable and its value to the $value variable, as demonstrated below.

Download  Run Code

 
2. The second syntax traverses the array and assigns the current element’s value to the $value variable on each iteration. To print the key and value from an associative array using this syntax, you can iterate over the array containing all the keys of the array:

Download  Run Code

 
The list() function can be used to assign a list of variables in one operation. If you have an array of arrays, you can unpack the nested array elements using list(), as follows:

Download  Run Code

 
It is possible to iterate over multidimensional arrays using nested foreach loops. Here’s a simple example for a two-dimensional array:

Download  Run Code

2. Using for loop

Finally, you can iterate over the array using a regular for loop. The idea is to loop from the 0th index to the size of the array, and access its elements using the array’s manual access notation.

Download  Run Code

That’s all there is to iterating over an associative array in PHP.