Let's make some examples:
array("Paul", "", "Daniel") // false
array("Paul", "Daniel") // true
array("","") // false
What's a neat way to work around this function?
true as a third parameter, in_array will do a loose comparison, so it'll give the same results with array("Paul", 0, "Daniel"), array("Paul", "", "Daniel") or array("Paul", false, "Daniel"). So if the op only wants to match empty string, he could just pass true as the third parameter.false if a 0 is in the array, and only on an empty string, just pass true as the third parameter.The answer depends on how you define "empty"
$contains_empty = count($array) != count(array_filter($array));
this checks for empty elements in the boolean sense. To check for empty strings or equivalents
$contains_empty = count($array) != count(array_filter($array, "strlen"));
To check for empty strings only (note the third parameter):
$contains_empty = in_array("", $array, true);
So array_filter() will remove empty the elements from the array and then return this array.
Comparing the returned array to the original array would not be the same.
Meaning the array contains one or more empty elements.
$array = array("Paul", "", "Daniel");
if($array != array_filter($array)) {
echo "Array contains empty values.";
}
array_filter will remove entities that are "false" (=empty) and return the array back without empty elements at it. Meaning if the data is not equal to the original array, the array contains empty values.Not exactly the answer to the question, but many visitors come here by searching for a solution to this slightly different case:
This would be a simple solution with implode(), that will fit to some needs
function testIfEmpty($array) {
$flat = implode('', $array);
return !empty($flat):
}
function testEmpty($array) {
foreach ($array as $element) {
if ($element === '')
return false;
}
return true;
}
Please check out the comments down below for more information.
Since I do enjoy me some fancy anonymous functions here is my take on it. Not sure about performance, but here it is:
$filter = array_filter(
["Paul", "", "Daniel"],
static function ($value) {
return empty($value); // can substitute for $value === '' or another check
}
);
return (bool) count($filter);
Logically explained. If anonymous returns true, it means that it found an empty value. Which means the filter array will contain only empty values at the end (if it has any).
That's why the return checks if the filter array has values using count function.
The (bool) type cast is equivalent to return count($filter) === 0.
May you all find the happiness you seek.