php - (Why) should I test if an array is empty prior to a for loop? -


given empty array $items = array();

why should use following code (which i've seen used before):

if (count($items) > 0) {    foreach ($items $item) // stuff here } 

instead of just

foreach ($items $item) // stuff here 

if count($items) === 0 loop won't execute anyway??

you don't need check. see lots of code check, it's unnecessary, , think it's due ignorance on part of programmer. similar pattern see after database queries:

if (mysqli_num_rows($stmt) > 0) {     while ($row = mysqli_fetch_assoc($stmt)) {         ...     } } 

this test unnecessary; if no rows found, first fetch return false, , loop stop.

the case it's useful if want tell user there no results, instead of displaying empty table. might do:

if (count($items) > 0) {     echo "<table>";     foreach ($items $item) {         // display table row     }     echo "</table>"; } else {     echo "<b>no data found!</b>"; } 

Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -