doubeishuai6598 2016-09-23 08:54
浏览 33

在循环之前检查(使用PHP)变量的正确方法?

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?

  • 写回答

2条回答 默认 最新

  • douguachan2879 2016-09-23 08:57
    关注

    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;
    }
    
    评论

报告相同问题?