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

7

28

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!

Rici answered 23/8, 2013 at 11:22 Comment(3)
Did you try if(!empty($csv_array[0]))?Closed
@Closed that will never ever get execute...because OP said its o index always empty...Mirna
If your file has a fixed format whenever it is empty, you could find the size occupied by an empty array containing file and use it to know if your array is empty? This is just a hack-y method, such methods are what you call as thinking out of the box ;) Although for this method to work, you need to make sure that the file content size is constant whenever the array is empty. :)Spitzer
M
19

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
}
Mirna answered 23/8, 2013 at 11:27 Comment(2)
Definitely the easiest way to go about this. Can't believe I didn't think of that haha. Thanks mate!Rici
What if the variable is not set? Which could throw an Error Notice.Portiaportico
L
49

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;
Lahdidah answered 23/8, 2013 at 11:36 Comment(1)
This is the better answer, if you don't know what your data is or what indices will exist. Thanks.Manofwar
M
19

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
}
Mirna answered 23/8, 2013 at 11:27 Comment(2)
Definitely the easiest way to go about this. Can't believe I didn't think of that haha. Thanks mate!Rici
What if the variable is not set? Which could throw an Error Notice.Portiaportico
C
7

If you don't know the structure of the multidimensional array

public function isEmpty(array $array): bool
{
    $empty = true;

    array_walk_recursive($array, function ($leaf) use (&$empty) {
        if ($leaf === [] || $leaf === '') {
            return;
        }

        $empty = false;
    });

    return $empty;
}

Just keep in mind all leaf nodes will be parsed.

Chigoe answered 30/3, 2017 at 20:43 Comment(1)
Works well on 5.4.*, with minor adjustments: sandbox.onlinephpfunctions.com/code/…Timmytimocracy
K
4

Combine array_filter() and array_map() for result. ( Result Test )

<?php
    $arrayData = [
        '0'=> [],
        '1'=> [
            'question1',
            'answer1',
            'answer2',
            'answer3',
            'answer4'
        ],
        '2'=> [
            'question1',
            'answer1',
            'answer2',
            'answer3',
            'answer4'
        ]
    ];

    $arrayEmpty = [
        '0' => [],
        '1' => [
            '1' => '',
            '2' => '',
            '3' => ''
        ]
    ];

    $resultData = array_filter(array_map('array_filter', $arrayData));
    $resultEmpty = array_filter(array_map('array_filter', $arrayEmpty));

    var_dump('Data', empty($resultData));
    var_dump('Empty', empty($resultEmpty));
Kataway answered 12/10, 2019 at 4:12 Comment(0)
P
1

just to be on the save side you want it to remove the empty lines ? or do you want to return if any array is empty ? or do you need a list which positions are empty ?

this is just a thought and !!! not tested !!!

/**
 * multi array scan 
 * 
 * @param $array array
 * 
 * @return bool
 */
function scan_array($array = array()){
  if (empty($array)) return true;

  foreach ($array as $sarray) {
    if (empty($sarray)) return true;
  } 

  return false;
}
Panettone answered 23/8, 2013 at 11:30 Comment(0)
E
0

You could possibly use an all rounder recursive function to check if any of the nested arrays are truthy.

Implementation would look like this:

function array_is_all_empty(array $array): bool
{
    foreach ($array as $value) {
        if (is_array($value) && !array_is_all_empty($value)) {
            return false;
        }

        if (!is_array($value) && !empty($value)) {
            return false;
        }
    }

    return true;
}

This will return true if the nested array is fully empty.

Eugeneeugenia answered 2/7 at 8:15 Comment(0)
L
-2

You can use array_push to avoid this situation,

$result_array = array();

array_push($result_array,$new_array);

refer array_push

Then you can check it using if (!empty($result_array)) { }

Libeler answered 23/8, 2013 at 11:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.