如何减少给定PHP代码段中的缩进级别

How to refactor this snippet of code, to reduce indentation level by one? I just wonder is it possible in PHP to write this code in a diffrent way, with just one level of indentation.

The code:

private function isArrayMatchingCriteria(array $array) {
    foreach($array as $element) {
        if (! $this->isElementMatchingCriteria($element) {
            return false;
        }
    }
    return true;
}

Please take into consideration, that:

  • this code doesn't always iterate over all array elements - so combination of count + array_filter / array_map isn't the same
  • it is easy to do by introducing a dedicated object attribute serving as a flag, but I'm looking for a way without introducing new attributes

If you're just looking to remove indentation, you could use:

private function isArrayMatchingCriteria(array $array) {
    foreach($array as $element) {
        if (!$this->isElementMatchingCriteria($element)) return false;
    }
    return true;
}

Use array_map, something like this:

class MyClass
{
    private function isElementMatchingCriteria( $element )
    {
        // DUMMY, replace with actual code
        if ( $element == "foo" || $element == "bar" ) {
            return true;
        } else {
            return false;
        }
    } // end is Element Matching Criteria

    public function isArrayMatchingCriteria(array $array)
    {
        $results = array_map( array( $this, "isElementMatchingCriteria"), $array );
        $isMatch = true;
        foreach ( $results as $result ) {
            $isMatch = $isMatch && $result;
        } // end foreach
        return $isMatch;
    } // end function isArrayMatchingCriteria
} // end MyClass

$myClass = new MyClass();
$array = array( "foo", "bar", "baz" );
$result = $myClass->isArrayMatchingCriteria( $array );
print_r( $result );