The Foreach Loop is a loop that works perfectly with arrays in PHP. You can use the for loop to iterate through an array, but to really shine, you need to use the foreach loop. The foreach loop has the following syntax.
For each array as key/value … or
For each key/value pair inside of an array.
It means that the foreach loop will loop through each array element and you will have access to each key/value pair of each element. This is great if you’re dealing with associative arrays. If the key is a string, you will not be able to access the element with a numerical index.
Sometimes you also need to display the key. For example, let’s say that you’re storing a to-do list inside of an associative array, where each key is the day of the week. You may need to display the key to the user as well. If you don’t, the structure of the foreach statement can be reduced.
foreach ($array as $value)
The above structure will only provide you access to the element’s value. You still have the advantage of looping through an array that has either non-numerical keys, or numerical but non-consecutive keys.
Read the full article on my website
https://www.dinocajic.com/php-foreach...
Code for this tutorial
https://github.com/dinocajic/php-7-yo...
Full Code
https://github.com/dinocajic/php-7-yo...
PHP Playlist
• PHP Tutorial
--
Dino Cajic
Author and Head of IT
Homepage: https://www.dinocajic.com
GitHub: https://github.com/dinocajic
Medium: / dinocajic
Instagram: / think.dino
LinkedIn: / dinocajic
Twitter: / dino_cajic
My Books
An Illustrative Introduction to Algorithms
https://www.amazon.com/dp/1686863268
Laravel Excel: Using Laravel to Import Data
https://amzn.to/4925ylw
Code Along With Me - PHP: From Basic to Advanced PHP Techniques
https://amzn.to/3M6tlGN