In PHP, you can use a loop to iterate through the elements of an indexed array. Here’s an example using a for loop:
$numbers = array(1, 2, 3, 4, 5); for ($i = 0; $i < count($numbers); $i++) { echo $numbers[$i] . " "; }
In this example, we create an indexed array of numbers and assign it to the variable $numbers . We then use a for loop to iterate through the elements of the array using the index numbers. The loop runs until the index number is equal to the length of the array (which is obtained using the count() function). Inside the loop, we use echo to output the value of each element in the array followed by a space.
Here’s another example using a foreach loop:
$fruits = array("apple", "banana", "orange"); foreach ($fruits as $fruit) { echo $fruit . " "; }
In this example, we create an indexed array of fruits and assign it to the variable $fruits. We then use a foreach loop to iterate through the elements of the array. Inside the loop, we assign each element to the variable $fruit and use echo to output its value followed by a space.
Note that the foreach loop is generally more concise and easier to read than the for loop when iterating through an indexed array.