Quantcast
Viewing all articles
Browse latest Browse all 11

Foreach Looping

Hi there! It’s been a few days since we met last, so I think it’s time to get right back into arrays! We talked about the first type of array last week –  the Indexed Array.
We are almost ready to talk about the next array called the Associative array.

However before we get there, we will talk about the last looping that we didn’t get to , because this type of looping actually only works with arrays! So just hang in there, and let us learn one more type of loop and next lesson we will get to the second type of array!

The outline of the foreach loop is as follows;

foreach ($array as $value) {

code to be executed;
}

This means, each time the loop is running, the value of the current array element is assigned to $value. The array will be moved by one until it reaches the last array.

This might seem a bit confusing, so let us look at the example below to understand.

<?php
$cars = array(“volvo”, “BMW”, “Honda”, “Lexus”);foreach ($cars as $value) {
echo “$value <br>”;
}
?>

The output of this will be a list of the cars looking like this:

volvo
BMW
Honda
Lexus


Viewing all articles
Browse latest Browse all 11

Trending Articles