iterate over an array in php

To iterate over an array in PHP, you can use a foreach loop. The syntax for the loop is as follows:

main.php
<?php

$array = array('apple', 'banana', 'orange');

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

?>
114 chars
10 lines

In the above example, we have an array containing 'apple', 'banana', and 'orange'. We use the foreach loop to iterate over each value in the array and print it out. The loop will continue until all the values in the array have been iterated over.

The output of the above code will be:

main.php
apple
banana
orange
20 chars
4 lines

You can also use the foreach loop to iterate over the keys and values of an associative array. The syntax for this is as follows:

main.php
<?php

$fruits = array('apple' => 'red', 'banana' => 'yellow', 'orange' => 'orange');

foreach ($fruits as $key => $value) {
    echo $key . ' is ' . $value . '<br>';
}

?>
173 chars
10 lines

In this example, we have an associative array containing fruits and their colors. We use the foreach loop to iterate over each key-value pair in the array and print out the key and value. The output of the above code will be:

main.php
apple is red
banana is yellow
orange is orange
47 chars
4 lines

gistlibby LogSnag