13 of 110 menu

The foreach Loop PHP Array

The foreach loop is used to iterate through all elements of an array.

Let's say we have the following array:

<?php $arr = [1, 2, 3, 4, 5]; ?>

Let's output its elements to the screen:

<?php $arr = [1, 2, 3, 4, 5]; foreach ($arr as $elem) { echo $elem; } ?>

Code execution result:

12345

Associative Array

You can also iterate and output all elements of an associative array.

Let's say we have the following array:

<?php $arr = ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'c' => 5]; ?>

Let's output its keys and elements to the screen:

<?php $arr = ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5]; foreach ($arr as $key => $elem) { echo $key . ' - ' . $elem . '<br>'; } ?>

See Also

English
БеларускаяEspañolРусский
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline