I have an array that is multidimensional and I need to test whether an offset exists. My reading of the PHP manual for array_key_exists makes sense for a single-dimension array.

My script takes results returned from the database and arranges them this way:

Array
(
    [1] => Array
        (
            [0] => Array
                (
                    [merged] => 0
                    [ingr_qty] => 1
                    [ingr] => pork tenderloin
                )
            [1] => Array
                (
                    [merged] => 0
                    [ingr_qty] => ⅓ roll
                    [ingr] => sausage meat
                )
        )
    [3] => Array
        (
            [0] => Array
                (
                    [merged] => 0
                    [ingr_qty] => 2 tbsp
                    [ingr] => finely chopped onion
                )
            [1] => Array
                (
                    [merged] => 0
                    [ingr_qty] => ⅓ cup
                    [ingr] => cranberry sauce
                )
        )
}

It would be tedious to explain why the array is written in this fashion. So please accept that it needs to be this way to facilitate making a table later in the script.

Occasionally, the pairs are not balanced. Using the above example, data occasionally comes out like this:

Array
(
    [1] => Array
        (
            [0] => Array
                (
                    [merged] => 0
                    [ingr_qty] => 1
                    [ingr] => pork tenderloin
                )
            [1] => Array
                (
                    [merged] => 0
                    [ingr_qty] => ⅓ roll
                    [ingr] => sausage meat
                )
        )

    [3] => Array
        (
            [0] => Array
                (
                    [merged] => 0
                    [ingr_qty] => 2 tbsp
                    [ingr] => finely chopped onion
                )
        )
}

Without the existence of an Array[3][1] key, PHP throws an error of 'Undefined offset' when making the table.

The circumstance will always occur on the last element of the first-level array and element [1] of the second-level array.

To point to elements of the array in my script, it's defined as $row[$z][$y]. How can I check if $row[$z][1] exists?

How about

if (isset($row[$z][1])) {
...

Hi Chris,

At first I didn't think this was going to work, based on "Example #2 array_key_exists() vs isset()" located at http://php.net/manual/en/function.array-key-exists.php. But on reading more closely, the reason for a FALSE would be due to the value of the element tested equal to NULL.

Thanks for the help! :)