$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
The in_array() function searches an array for a specific value. Note: If the search parameter is a string and the type parameter is set to TRUE, the search is case-sensitive.
To check if a value is not in array array, use the indexOf() method, e.g. arr. indexOf(myVar) === -1 . If the indexOf method returns -1 , then the value is not contained in the array.
The is_array() is an inbuilt function in PHP. The is_array() function is used to check whether a variable is an array or not. Parameter: This function accept a single parameter as mentioned above and described below: $variable_name: This parameter holds the variable we want to check.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With