Foreach in PHP

While developing web applications there are always routines that display some kind of information on the screen. Apart from displaying data, it is absolutely crucial to be able to modify it as well in a massive scale. Such functionality calls for the foreach structure.

Foreach is essentially a structure that is responsible for traversing an iterable given some expression. With each iteration, foreach may execute a defined action to the data, either to modify the value, create a new iterable or a construct for some kind of preview routine.

To use foreach effectively you need to know how the iterable looks like. There are iterables that their keys aren’t defined such as normal arrays, there are others that do have defined keys such as associative arrays. The most effective way to use foreach is by applying it to an object of a certain class. Let’s review some examples:

Applying foreach using a normal array with numerical indices:

$arr = array(1,2,3,4,5);
foreach ($arr as $item) {
    echo $item . ', ';
}
// prints: 1, 2, 3, 4, 5

Note that the $item variable can be whatever you want. There’s no limitation there. You could use something like $i or $it or what have you. Now, working with associative arrays can be way more interesting than the previous example. Observe:

$arr = array(
array(
'firstname' =>  'Jane',
'lastname'  =>  'Doe'
),
array(
'firstname' =>  'John',
'lastname'  =>  'Doe'
)
);
foreach($arr as $person) {
echo $person['firstname'] . ' ' . $person['lastname'] . '<br>';
}
/* prints:
Jane Doe
John Doe */

As you can see, associative arrays are more versatile and more human-friendly when there’s a need to describe the data. The array contains two sub arrays that are comprised by two corresponding key value pairs. A key value pair describes the relationship between a label and the value that describes. Note that you need the key to access the value, hence the $person[‘firstname’] and $person[‘lastname’] parts. There is however a way to extract each key and value within the confines of the foreach code block.

$user = array(
    'firstname' =>  'Jane',
    'lastname'  =>  'Doe'
);

foreach($user as $prop=>$value) {
    echo $prop . ' : ' . $value . '<br>';
}

/* prints:
firstname : Jane
lastname : Doe
*/

You can always break down that custom variable within the foreach construct into its two subparts, the key and value. Then you can choose which one to use depending your use case. But what happens when we traverse objects?

class Person {
public $first, $last;
public function __construct($first, $last) {
$this->first = $first;
$this->last = $last;
}
}

$people = array(
new Person('Jane', 'Doe'),
new Person('John', 'Doe')
);

foreach($people as $p) {
echo $p->first . ' ' . $p->last . '<br>';
}
/* prints:
Jane Doe
John Doe
*/

The idea here is similar to the associative track. The difference however it’s in the way we access the information. When we’re messing with objects, the data that we access comes from properties. More on that on a different article. The important thing to keep in mind here is that you need to use the right arrow -> to access each property of the object, $first and $last in this case. Sometimes there’s a need to change or modify the data of an array without creating a new one to store the modified data. That can be done easily using the & operator. This operator will be applied as a prefix to the custom variable of our choice.
Afterwards if we assign anything within the block of foreach to each specific property or what not, you change it without losing the array that you have and you are essentially modifying it.

$arr = [1,2,3,4,5,6];
foreach($arr as &$num){
    $num = pow($num, 3);
    echo $num . ' ';
}
unset($num);
// prints: 1 8 27 64 125 216

As you can see we modified the data by overwriting each value with its cubed calculation. Notice the unset at the end. That unset function will break the reference of the last element of the array so you can re-apply this technique without experience any unexpected modifications while re-writing the data. To view the data is a matter of how you want to tinker with HTML and how you create the template. For instance, suppose you want to populate the options of a select box that exists on a form. You would do something like this:

<select name="gender" id="gender">
    <?php foreach(array('male', 'female', 'non-binary') as $g): ?>
        <option value="<?php echo $g ?>">
            <?php echo $g ?>
        </option>
    <?php endforeach ?>
</select>