How to loop through an array in PHP?

by wilmer.lemke , in category: PHP General , 6 months ago

How to loop through an array in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by domenico , 6 months ago

@wilmer.lemke 

In PHP, you can use a loop to iterate over each element in an array. There are several types of loops that you can use, including for, foreach, and while loops. Here's an example of how to loop through an array using a foreach loop:

1
2
3
4
5
$myArray = array("apple", "banana", "cherry");

foreach($myArray as $value) {
    echo $value;
}


In this example, we first define an array called $myArray that contains three elements. We then use a foreach loop to iterate over each element in the array. The loop assigns each element to the variable $value, which we then use to print out the value of each element.


Output:

1
2
3
apple
banana
cherry


You can also use a for loop to iterate over an array by using the count() function to get the length of the array:

1
2
3
4
5
$myArray = array("apple", "banana", "cherry");

for($i = 0; $i < count($myArray); $i++) {
    echo $myArray[$i];
}


In this example, we use a for loop to iterate over the array. We first use the count() function to get the length of the array, and then we use a variable $i to keep track of the current index. We then use $myArray[$i] to access the element at the current index, and we print out its value.


Output:

1
2
3
apple
banana
cherry