This question already has an answer here:
- Invalid argument supplied for foreach() 18 answers
Not a major problem but I was wondering if there is a cleaner way to do this. It would be good to avoid nesting my code with an unnecessary if statement. If $items
is empty php throws an error.
$items = array('a','b','c');
if(!empty($items)) { // <-Remove this if statement
foreach($items as $item) {
print $item;
}
}
I could probably just use the '@' error suppressor, but that would be a bit hacky.
The best way is to initialize every bloody variable before use.
It will not only solve this silly "problem" but also save you a ton of real headaches.
So, introducing $items as
$items = array();
is what you really wanted.I think the best approach here is to plan your code so that $items is always an array. The easiest solution is to initialize it at the top of your code with $items=array(). This way it will represent empty array even if you don't assign any value to it.
All other solutions are quite dirty hacks to me.
If variable you need could be
boolean false
- eg. when no records are returned from database orarray
- when records are returned, you can do following:Approach with cast(
(Array)$result
) produces an array of count 1 when variable isboolean false
which isn't what you probably want.You can check whether $items is actually an array and whether it contains any items: