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!
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With