0

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?

2
Contributors
2
Replies
4
Views
5 Years
Discussion Span
Last Post by dwlamb
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.