php · PHP basics
What does the 'foreach' loop in PHP do?
Answers
- It loops through each character of a string
- It loops through each key-value pair in an array
- It executes a block of code a specific number of times
- It iterates through numeric indexed arrays only
"; } ``` The output will then be: ``` The color of Apple is Red. The color of Banana is Yellow. The color of Orange is Orange. ``` Notably, the `foreach` loop in PHP is flexible and can be used with both indexed arrays and associative arrays. Even multidimensional arrays can be iterated over with nested `foreach` loops. In PHP programming, it's considered best practice to use `foreach` when you want to iterate over the elements in an array irrespective of their keys. It's simple, elegant, and more readable than other types of loops. However, one should always be cautious not to modify the array within the loop to avoid unpredictable behavior.