I have the array $var, and I\'d like to return FALSE if one or more element in the array are empty (I mean, the string are \"\").
I think that array_filter()
Or explicitly, as suggested by @Ancide:
$var = array("lorem", "ipsum", "dolor");
$emptyVar = array("lorem", "", "dolor");
function has_empty($array) {
foreach ($array as $value) {
if ($value == "")
return true;
}
return false;
}
echo '$var has ' . (has_empty($var) ? 'empty values' : 'no empty values');
echo '<br>';
echo '$emptyVar has ' . (has_empty($emptyVar) ? 'empty values' : 'no empty values');
EDIT:
I wasn't sure at first if array_search()
stops at first occurrence. After verifying PHP's source it seems that array_search()
approach should be faster (and shorter). Thus @Wh1T3h4Ck5's version would be preferable, I suppose.
If you really want to check if one or more empty strings exists, it's simple. You can do,
in_array('', $var, true);
It returns true if empty string(''
) exists in at-least any one of the array values, false otherwise.
You can refer this similar question too,
how to check if an array has value that === null without looping?
If you want to have a function which checks if a item in the array is false you could write your own function which does:
The array_filter takes a array and a function, then iterates through the array and sends in each item in the specified function. If the function returns true the the item is kept in the array and if the function returns false the item is taken out of the array.
You see the difference, right?
function emptyElementExists($arr) {
return array_search("", $arr) !== false;
}
Example:
$var = array( "text1", "", "text3" );
var_dump( emptyElementExists($var) );
Output:
bool(true)
Reference
if (array_search('', $var)!==false) return FALSE;