OneBite.Dev - Coding blog in a bite size

Iterate Over An Array In PHP

Code snippet for how to Iterate Over An Array In PHP with sample and detail explanation

Iterating over an array in PHP is a practice that is commonplace in web development. This guide will help you understand the basics of this process, providing an example code snippet and explaining how it works.

Code snippet: Iterating Over an Array in PHP

Here’s a simple example of how to iterate over an array in PHP:

<?php
$arr = array("a", "b", "c", "d", "e");

foreach ($arr as $value) {
    echo $value . '<br>';
}
?>

The foreach loop is used in this snippet to iterate over the array.

Code Explanation: Iterating Over an Array in PHP

In our example, we have an array $arr that contains 5 elements: ‘a’, ‘b’, ‘c’, ‘d’, and ‘e’.

To iterate over each element in the array, we’ll use the foreach loop. The foreach loop goes through each element of an array, executing the code enclosed within its block for each iteration.

In our foreach loop structure:

foreach ($arr as $value) {
    echo $value . '<br>';
}
  • $arr is the array we’re iterating over.
  • $value is a placeholder variable that temporarily takes on the value of the current element in the array during each iteration of the loop. You can name this variable anything you want.

On each iteration of the foreach loop, we’re using echo to output the current element ($value). The .'<br>' at the end simply adds a line break after each element, just to make our output neater.

Therefore, the output of this code will print each element of the array on a new line:

a
b
c
d
e

With this understanding, you can now iterate over arrays in PHP to access and manipulate each element in a sequence. Displaying all the elements as done in this example is just one of the countless operations you can perform on an array.

php