OneBite.Dev - Coding blog in a bite size

Loop Array In PHP

Code snippet for how to Loop Array In PHP with sample and detail explanation

Looping through arrays in PHP is a fundamental task that every PHP developer must master. It allows for the efficient manipulation of data within arrays, therefore broadening our ability to handle data.

Code snippet for Loop Array In PHP

This is a basic example on how to loop an array in PHP:

$array = array("apple", "banana", "cherry");

foreach($array as $fruit){
  echo $fruit . "<br>";
}

Code Explanation for Loop Array In PHP

Something you should know about arrays in PHP, they are simply variables that allow us to store multiple values. In this example, we created an indexed array named $array with three string values: “apple”, “banana”, and “cherry”.

The foreach construct in PHP provides an easy way to iterate over arrays. The foreach loop works only on arrays, and is used to loop through each key/value pair in an array.

In our code, $array is the array that we’re going to loop through, the loop will continue for as many items as there are in this array and $fruit is the temporary variable we’re using to represent the current item in this loop. On each iteration, $fruit holds the current element from the array.

We then use the echo statement to output the value of each loop iteration followed by a break <br>, this means each fruit will be printed on a new line in the browser.

So, for our code, it will print:

apple
banana
cherry

To sum up, loops are a powerful tool that allow you to perform actions on each item in an array in a quick and easy way. The foreach loop is specially designed to manipulate arrays in PHP, making it an essential part of any PHP developer’s toolkit.

php