Search code examples
phparraysmultidimensional-array

How to check if a multidimensional array is empty or not?


Basically, I have a multidimensional array, and I need to check whether or not it is simply empty, or not.

I currently have an if statement trying to do this with:

if(!empty($csv_array)) 
{   
    //My code goes here if the array is not empty
}

Although, that if statement is being activated whether the multidimensional array is empty or not.

This is what the array looks like when empty:

Array
(
    [0] => Array
        (
        )

)

This is what the array looks like when it has a few elements in it:

Array
(
    [0] => Array
        (
        )

    [1] => Array
        (
            [1] => question1
            [2] => answer1
            [3] => answer2
            [4] => answer3
            [5] => answer4
        )

    [2] => Array
        (
            [1] => question2
            [2] => answer1
            [3] => answer2
            [4] => answer3
            [5] => answer4
        )

    [3] => Array
        (
            [1] => question3
            [2] => answer1
            [3] => answer2
            [4] => answer3
            [5] => answer4
        )

)

My array elements always start at 1, and not 0. Long story why, and no point explaining since it is off-topic to this question.

If needed, this is the code that is creating the array. It is being pulled from an uploaded CSV file.

$csv_array = array(array());
if (!empty($_FILES['upload_csv']['tmp_name'])) 
{
    $file = fopen($_FILES['upload_csv']['tmp_name'], 'r');
}

if($file)
{
    while (($line = fgetcsv($file)) !== FALSE) 
    {
        $csv_array[] = array_combine(range(1, count($line)), array_values($line));
    }

    fclose($file);
}

So in conclusion, I need to modify my if statement to check whether the array is empty or not.

Thanks in advance!


Solution

  • So simply check for if the first key is present in array or not.

    Example

    if(!empty($csv_array[1])) 
    {   
        //My code goes here if the array is not empty
    }