How to Iterate Over an Array in PHP? (original) (raw)

Last Updated : 13 Mar, 2025

Arrays are fundamental data structures in PHP, and the ability to iterate through them is crucial for manipulating and processing data. In this article, we will explore various approaches to iterate through arrays in PHP.

Table of Content

Using for Loop

The PHP for loop is a basic way to iterate through an array. It is useful when you need to access array elements by their index.

PHP `

length=count(length = count(length=count(arr); for ($i = 0; i<i < i<length; $i++) { echo arr[arr[arr[i] . ' '; } ?>

`

Using foreach Loop

The PHP foreach loop is an method to iterate through an array. There is no need of index number in foreach loop.

PHP `

`

Using while Loop with each() Function

The PHP each() function can be used in combination with a while loop to iterate through an array while maintaining the internal pointer.

PHP `

' . $element['value'] . "\n"; } ?>

`

Output

0 => apple 1 => banana 2 => cherry

Using array_walk() with a callback function

In PHP, `array_walk()` iterates through an array, applying a user-defined callback function to each element. The callback receives each array element as an argument, allowing for custom operations on array values without needing to manage iteration explicitly.

PHP `

`

Using array_map() with a Callback Function

The array_map() function in PHP applies a callback function to each element of an array, creating and returning a new array with the results of the callback function.

PHP `

newArray=arraymap(′increment′,newArray = array_map('increment', newArray=arraymap(increment,array); // Print the new array foreach ($newArray as $val) { echo $val . ' '; } ?>

`

Using array_reduce()

This approach uses array_reduce() to apply a callback function to each element of the array, reducing the array to a single cumulative value.

PHP `

`

Output

apple banana cherry