Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 227
Fizzix Avatar asked Sep 06 '25 03:09

Fizzix


1 Answers

You can filter the array, by default this will remove all empty values. Then you can just check if it's empty:

$filtered = array_filter($csv_array);
if (!empty($filtered)) {
  // your code
}

Note: This will work with the code posted in your question, if you added another dimension to one of the arrays which was empty, it wouldn't:

$array = array(array()); // empty($filtered) = true;
$array = array(array(array())); // empty($filtered) = false;
like image 95
billyonecan Avatar answered Sep 08 '25 00:09

billyonecan