PHP: testing for existence of a cell in a multidimensional array

后端 未结 4 1010
忘了有多久
忘了有多久 2021-02-01 15:11

I have an array with numerous dimensions, and I want to test for the existence of a cell.

The below cascaded approach, will be for sure a safe way to do it:



        
4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-01 15:27

    isset() is the cannonical method of testing, even for multidimensional arrays. Unless you need to know exactly which dimension is missing, then something like

    isset($arr[1][2][3])
    

    is perfectly acceptable, even if the [1] and [2] elements aren't there (3 can't exist unless 1 and 2 are there).

    However, if you have

    $arr['a'] = null;
    

    then

    isset($arr['a']); // false
    array_key_exists('a', $arr); // true
    

    comment followup:

    Maybe this analogy will help. Think of a PHP variable (an actual variable, an array element, etc...) as a cardboard box:

    • isset() looks inside the box and figures out if the box's contents can be typecast to something that's "not null". It doesn't care if the box exists or not - it only cares about the box's contents. If the box doesn't exist, then it obviously can't contain anything.
    • array_key_exists() checks if the box itself exists or not. The contents of the box are irrelevant, it's checking for traces of cardboard.

提交回复
热议问题