Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in_array check for non false values

Tags:

php

$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
like image 237
ihtus Avatar asked Feb 12 '13 16:02

ihtus


People also ask

What does the in_array () function do?

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.

How do you check if a value is not in an array?

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.

Is PHP an 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.


1 Answers

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.

like image 153
Fabian Schmengler Avatar answered Oct 19 '22 07:10

Fabian Schmengler