example:
foreach($boxes as $box) {
echo "$box \n";
}
Used to be fairly easy, I could just wrap the foreach around a check like:
if(is_array($boxes) && count($boxes) > 0) {
//foreach loop here
}
Without having to worry about a warning getting thrown if for whatever reason bad input was passed to the $boxes array.
When Iterators, were added to the mix, this no longer works, as Iteratable objects are not arrays. So, I have a few solutions, but am wondering if there is a ‘best practice’ for this.
// 1:
if($boxes instanceof Traversable && count($boxes) > 0) {
//foreach loop here
}
// 2:
if($boxes && count($boxes) > 0) {
//foreach loops here
}
There are others, but these seem like the most obvious. Anyone have any suggestions. PHP docs seem to be silent.
You shouldn’t have the
count($array) > 0 part, because a) foreach works fine with empty arrays, b) objects can beTraversableyet not beCountableand c) the value returned bycount()may even (for objects) be disconnected from the number of items the traversal will yield.And #1 there is different from #2; since
$boxes instanceOf Traversableis not the same as$boxes. Also note that internally arrays don’t implement Traversable.I would go with
This still doesn’t guarantee that the traversal will be successful; the iteration may throw an exception at any point. In particular, for some classes it may not make sense to traverse them more than once.