6

Can anybody show example of using forAll method of Doctrine\Common\Collections\ArrayCollection?

2 Answers 2

15

It's pretty straightforward. The class you linked to implements the forAll method in a following manner:

foreach ($this->_elements as $key => $element) {
     if ( ! $p($key, $element)) {
         return false;
     }
}

So, based on that you should invoke the forAll like:

$collection = ... #some data

$collection->forAll(function($key, $item){
    // Your logic here, based on $key and $item
});

Hope this help....

EDIT (the example):

  • You have an object of entity Student, which has a OneToMany to student's marks.
  • You want to check if student has passed all the subjects he/she elected

    $student = ....
    $allPassed = $student->getMarks()->forAll(function($key, $mark){
        return $mark->getValue() != 'F';
    });
    

The $allPassed will hold TRUE if all marks were either 'A', 'B', 'C' or 'D'. Even if one of them were F if will be FALSE.

1
  • I can't understand how $key and $element parameters passed to the Closure, but now I understood. Thanks! Jun 11, 2014 at 11:51
4

I would like to highlight that forAll method exits as soon as the inner function returns a false.

Following the example of Perovic, take for instance that the $student has 10 marks, where only one is an 'F'.

If the 'F' mark is the 10th element of the array, the function $mark->getValue() will be invoked 10 times. On the other hand, if the 'F' mark is the first element of the array, $mark->getValue() will be invoked only once, since the function immediately returns false, and forAll method stops evaluating.

1
  • The first sentence should actually be stated as returns a falsey value Since it will exit when the value is 0, false, null, "" Actual source can be seen in the accepted answer. Results: 3v4l.org/4g6DJ So in effect the method can be thought of as testAll()
    – Will B.
    Nov 30, 2017 at 14:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.