– The foreach loop in php works only with Arrays or Objects
– Foreach loop in php used to loop through various values within an array
– It can used to loop through indexed as well as associated array
For every single iteration the value of current index is assigned to the $value and can be accessed within the array body with $value variable.
Syntax
For every single iteration the value of current index is assigned to the $value and can be accessed within the array body with $value variable.
Example
In the above example, the languages
array stores some languages name. The foreach loop uses this array to get values in language
variable one by one. The above loop prints all the language one by one.
Output
php java python javascript
NOTE – foreach
does not support the ability to suppress error messages using @
.
You can also use foreach() loop to traverse multi dimensional arrays using list() method. Consider the example below
The above example will output –
A:1, B:2 A:3, B:4
You can provide fewer elements in the list() than there are in the nested array, in which case the leftover array values will be ignored.
Also Check – If statement in php
Below are some questions related to foreach loop –
- why to use foreach loop
- when to use foreach loop
- how foreach loop works
- difference between for loop and foreach loop
Reference – foreach loop