Php simple foreach loop with HTML
Quickly generate an HTML list from an array with PHP. Combine a foreach
loop with HTML markup:
This creates a list item (<li>
) for each element in $items
, using htmlspecialchars
to prevent any sneaky security issues.
Dealing with conditionals
Nothing is truly simple. Sometimes you need conditional formatting for your items. For example, if you really like bananas:
A conditional class has been added to a list item based on the item's value.
The associative array dance
Much like a good dance partner, foreach
loops work well with associative arrays allowing access to both the key and value:
Your dance card (<ul>
) now describes the type and color of each fruit dancing at the ball.
From simply list to HTML table
Let's dress our foreach
for a spiffy occasion. When presenting database results, for instance, a foreach
dressed in a HTML table can impress:
Dressed up, our loop walks down the aisle, each row shining with user data.
Dynamic dropdown menus creation
The practicality of foreach
comes to the fore in dynamically populating dropdown menus:
This select element juggles options for each fruit, with the fruit name as display text.
Guarding against exceptions
Life isn't always a bowl of cherries. Facing empty arrays or invalid iterators outright can help prevent a white screen of death:
A quick check to ensure the array isn't empty prevents run-time errors and keeps Mr. Death Screen away.
Was this article helpful?