PHP- foreach Loop

The foreach loop allows us to print out all the contents of an array.

foreach Loop with Only Values

For example, we create the following array in PHP:

Using the foreach loop in the following format below,
we can print out all the values of the above array:

Actual PHP Output

10
20
30
40

Foreach loop with Keys and Values

The other way a foreach loop can be used is to specify both the keys and values of an array.



Actual PHP Output

item1 is 10
item2 is 20
item3 is 30

Printing the key and value of an array can also work for arrays where only values are specified.

We have the following array in PHP:

The keys which will be created for this array by PHP are 0-3, to represent each element

To print out the above array, we use the code:

Actual PHP Output

Key 0 is 10
Key 1 is 20
Key 2 is 30
Key 3 is 40