Reputation: 2811
$array = array(
'vegs' => 'tomatos',
'cheese' => false,
'nuts' => 765,
'' => null,
'fruits' => 'apples'
);
var_dump(in_array(false, $array, true)); //returns true because there is a false value
How to check strictly if there is at least one NON-false (string, true, int) value in array using in_array only or anything but not foreach?
var_dump(in_array(!false, $array, true)); //this checks only for boolean true values
var_dump(!in_array(false, $array, true)); //this returns true when all values are non-false
Upvotes: 8
Views: 10169
Reputation:
How to check strictly if there is at least one NON-false (string, true, int) value in array using in_array only or anything but not foreach?
This is not possible because:
Then, INT and STRING data types can't be found just using an abstract (int) or (string)!
EDIT:
function get_type($v)
{
return(gettype($v));
}
$types = array_map("get_type", $array);
print_r($types);
RESULT:
Array
(
[vegs] => string
[cheese] => boolean
[nuts] => integer
[] => NULL
[fruits] => string
)
Upvotes: 0
Reputation: 24551
Actual solution below
Just put the negation at the right position:
var_dump(!in_array(false, $array, true));
Of course this will also be true if the array contains no elements at all, so what you want is:
var_dump(!in_array(false, $array, true) && count($array));
Edit: forget it, that was the answer for "array contains only values that are not exactly false", not "array contains at least one value that is not exactly false"
Actual solution:
var_dump(
0 < count(array_filter($array, function($value) { return $value !== false; }))
);
array_filter
returns an array with all values that are !== false
, if it is not empty, your condition is true.
Or simplified as suggested in the comments:
var_dump(
(bool) array_filter($array, function($value) { return $value !== false; })
);
Of course, the cast to bool
also can be omitted if used in an if
clause.
Upvotes: 11