1

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.

6
  • 1
    We cant tell anything from that image, try a var_dump and paste it. Commented Mar 28, 2020 at 15:12
  • I have updated the question with a var_dump of each array for each dimension. Commented Mar 28, 2020 at 15:18
  • 2
    Seems like it is a 3 dimensional array. Add another [0] in your isset Commented Mar 28, 2020 at 15:20
  • Please provide an example array to demonstrate the issue. Commented Mar 28, 2020 at 15:22
  • 1
    @DenverThomas We all have to start somewhere :) Commented Mar 28, 2020 at 15:33

1 Answer 1

1

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

$arr = [[]];
if (!count($arr[0])) {
    // do stuff
}  
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.