mattexx
mattexx

Reputation: 6606

Does PHP have an equivalent to Python's all()

Python has a nice all() (doc) method that returns true if all elements in an iterable are true, which is equivalent to:

def all(iterable):
    for element in iterable:
        if not element:
            return False
    return True

Is there a similarly nice way to do this in PHP?

Upvotes: 5

Views: 2336

Answers (3)

ikenas
ikenas

Reputation: 431

If all your values are boolean, this would be a simpler approach:

in_array(true,$array)

Upvotes: 0

dev-null-dweller
dev-null-dweller

Reputation: 29482

Closest to it may be array_filter, if no true element are found it will return empty array that evaluates to false.

On the second thought it's more like pythons any(). To emulate all() you will need if(array_filter($array) == $array) or even if(array_filter($array) == $array && $array) to exclude empty array.

Upvotes: 4

jabaldonedo
jabaldonedo

Reputation: 26582

There's no such function, but you can achieve the same effect with:

count(array_keys($array, 'yes')) == count($array)

Upvotes: 0

Related Questions