In the past, I’ve noticed that a lot of PHP beginners tend to struggle with the foreach loop. In some cases, it is because they have arrived from a language that only supports while loops and for loops.
Here is a basic example of a foreach loop:
<?php foreach($array as $item){ echo $item, '<br>'; }
In the loop above, I am simply printing out each item in $array.
However – What if you need to get the key / index of the item that you are currently iterating over? Well, there’s a slight modification that we can make:
<?php foreach($array as $key => $item){ echo $key . ":" . $item . "<br>"; }
The variable $key will contain the key / index of the current item inside the foreach loop. It’s that simple!