ihtus
ihtus

Reputation: 2811

in_array check for non false values

$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

Answers (2)

user1646111
user1646111

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:

  • String: this data type can contain any value, its not like boolean (true or false) or NULL.
  • INT: same as string, how to check for unknown?
  • Boolean: possible.
  • NULL: possible.

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

Fabian Schmengler
Fabian Schmengler

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

Related Questions