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 thi
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;
}
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)) { }
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
}
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));
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 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.