Before looping through a variable (supposed to be an array) I would make the following test:
if(
!empty($arrJobs) &&
is_array($arrJobs) &&
count($arrJobs)
){
foreach ($arrJobs as $item) {
//loop tasks
}
}
I've seen also using if(sizeof($arrJobs)>0) but in case $arrJobs isa integer (I can't trust the input) it would be through and I will try looping through a integer...weird.
Is there a more concise and comprehensive way to perform this test before looping through the array?
You don't need to check anything but is_array
: if it's empty, PHP simply won't loop.
Moreover a suggestion: if those if
had sense (not that case, but is helpful for this explanation) you should split with "early exit" (as coding style because it improves readability)
if (empty($arrJobs)) {
return;
}
if (!is_array($arrJobs)) {
return;
}
if (count($arrJobs)) {
return;
}
It is IMPORTANT to check if you're looping an ARRAY to FOREACH or else PHP will give you errors ... FOREACH expects parameter to be ARRAY..
You can use IS_ARRAY .. I believe that would be enough.
But checking it if empty would be VERY GOOD Practice... I'm using COUNT() to check if an ARRAY is empty.