Often you need to move through all the elements in a PHP array so that you can do something with each element’s value. For example, you may want to display each value in an HTML table, or give each element a new value.
In Counting PHP Array Elements Using count()
, I showed how you can use a for
loop along with the count()
function to loop through an array. However, there’s a much easier way to loop through arrays: the foreach
construct.
In this article you learn the basic syntax of foreach
, and see how to use it to loop through both indexed and associative arrays.