Checking for empty arrays: count vs empty

前端 未结 12 779
隐瞒了意图╮
隐瞒了意图╮ 2020-12-07 12:59

This question on \'How to tell if a PHP array is empty\' had me thinking of this question

Is there a reason that count should be used instead of e

12条回答
  •  没有蜡笔的小新
    2020-12-07 13:41

    Sometimes using empty is a must. For example this code:

    $myarray = array();
    
    echo "myarray:"; var_dump($myarray); echo "
    "; echo "case1 count: ".count($myarray)."
    "; echo "case1 empty: ".empty($myarray)."
    "; $glob = glob('sdfsdfdsf.txt'); echo "glob:"; var_dump($glob); echo "
    "; echo "case2 count: ".count($glob)."
    "; echo "case2 empty: ".empty($glob);

    If you run this code like this: http://phpfiddle.org/main/code/g9x-uwi

    You get this output:

    myarray:array(0) { } 
    case1 count: 0
    case1 empty: 1
    
    glob:bool(false) 
    case2 count: 1
    case2 empty: 1
    

    So if you count the empty glob output you get wrong output. You should check for emptiness.

    From glob documentation:

    Returns an array containing the matched files/directories, an empty array if no file matched or FALSE on error.
    Note: On some systems it is impossible to distinguish between empty match and an error.

    Also check this question: Why count(false) return 1?

提交回复
热议问题