array_key_exists($key, $array) vs !empty($array[$key])

前端 未结 4 1498
清酒与你
清酒与你 2021-01-01 18:09

I\'ve seen a lot of people do the former, is there any performance benefit doing one vs the other? Or is it just an eye candy? I personally use the latter every time as it i

4条回答
  •  情书的邮戳
    2021-01-01 18:39

    array_key_exists($key, $array) and !empty($array[$key]) can produce different results therefore it is not a matter of performance or preference.

                                  | array_key_exists($key, $array) | !empty($array[$key]) |
    +-----------------------------+--------------------------------|----------------------+
    | $array[$key] does not exist | false                          | false                |
    | $array[$key] is truthy      | true                           | true                 |
    | $array[$key] is falsey      | true                           | false                |
    

    You can see that the truth table is different for falsey values (false, 0, NULL, etc). Therefore !empty($array[$key]) is not suitable in situations where a falsey value could be considered present e.g. $array["number_of_children"] should not be tested for emptiness where the value 0 makes sense.


    You can use isset($array[$key]) which produces results identical to array_key_exists($key, $array) with exactly one exception:

                                          | array_key_exists($key, $array) | isset($array[$key]) |
    +-------------------------------------+--------------------------------|---------------------+
    | $array[$key] does not exist         | false                          | false               |
    | $array[$key] is truthy              | true                           | true                |
    | $array[$key] is falsey but not NULL | true                           | true                |
    | $array[$key] is NULL                | true                           | false               |
    

提交回复
热议问题