Reputation: 24375
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!
Upvotes: 29
Views: 41802
Reputation: 27364
So simply check for if the first key is present in array or not.
Example
if(!isset($csv_array[1]))
{
//My code goes here if the array is not empty
}
Upvotes: 19
Reputation: 47992
Considering a data payload of indeterminant depth, here are a few performant approaches.
Short circuit the closure of array_walk_recursive()
by catching a thrown exception upon encountering a leafnode. Demo
function hasNonEmptyArray(array $array): bool
{
try {
array_walk_recursive(
$array,
fn($v, $k) => throw new Exception("Found element $k\n")
);
return false;
} catch (Exception $e) {
echo $e->getMessage();
return true;
}
}
Return early from a foreach()
while looping the leaf nodes of a Recursive Iterator. Demo
function hasNonEmptyArray(array $array): bool
{
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
foreach ($iterator as $k => $v) {
echo "Found element $k\n";
return true;
}
return false;
}
Implement a userland recursive function to return true as soon as a leaf node is encountered. Demo
function hasNonEmptyArray(array $array): bool
{
foreach ($array as $k => $v) {
if (is_array($v)) {
if (hasNonEmptyArray($v)) {
return true; // pass deeper true outcome up the call chain
}
} else {
echo "Found element $k\n";
return true;
}
}
return false;
}
As for a lame answer which will not be terribly useful for future readers but will work for the asked question's context, just use if (!empty($csv_array[1])) {
because checking if key 1
exists and has a non-falsey value will be enough.
Upvotes: 0
Reputation: 11
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.
Upvotes: 0
Reputation: 537
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));
Upvotes: 4
Reputation: 9838
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.
Upvotes: 7
Reputation: 20260
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;
Upvotes: 51
Reputation: 91
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;
}
Upvotes: 1
Reputation: 1754
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)) { }
Upvotes: -2