What is the correct syntax for detecting an empty 2D array in PHP?

Viewed 44

What is the correct syntax to detect an empty 2 Dimensional array in PHP? I have attempted to do so myself using the functions "isset()" and "!empty()" for both "2dArray[0]" and "2dArray[0][0]", but even with an empty array the result comes back positive. Here is a snippet of code from one of the times where I tried this:

if(isset($strengths[0][0]) || isset($sizes[0][0]))
{
    print_r($strengths[0][0]);
    echo "<br>blah<br>";
    print_r($sizes[0][0]);
}

Yet the arrays are both empty. Using print_r we can even see that the arrays return nothing. Here is a picture example of a different attempt using isset(2dArray[0]):

example of apparently conflicting code

In the picture you can see the array is also empty again.

It's important to note that I can use 2dArray[1] perfectly; it detects that there there is no second row as expected, but that means I cannot have any instances where there is only 1 row in either 2D array because it is positioned at position 0 with nothing at position 1 to be detected anyway.

What am I doing wrong?

Edit 1: The code:

var_dump($strengths[0][0]);
var_dump($sizes[0][0]);

returns:

array(0) { } 
array(0) { } 

and the code:

var_dump($strengths[0]);
var_dump($sizes[0]);

returns:

array(1) { [0]=> array(0) { } } 
array(1) { [0]=> array(0) { } } 

Edit 2: This is my init:

$sizes[][] = array(); 

This is where data is set:

foreach($products as $product)
{
    //product information

    foreach($mods as $mod)
    {
        //mod information
        //when array is empty $mods is empty
        if ($modType == "SIZE")
        {
            $sizes[$si][0] = $modValue . $modValueSuffix;
            $sizes[$si][1] = $modPrice;
            $sizes[$si][2] = $modID;
            $si++;
            $strengthOrSize = true;
        }
     }
}

I believe I should have done $sizes[] = array(); for a 2D array. I overlooked this because it's such a short piece of code I did not give it much attention.

1 Answers

You can do this to detect if the sub array is empty:

$arr = [[]];
if (!count($arr[0])) {
    // do stuff
}  
Related