DusanKasan / Knapsack

Collection pipeline library for PHP
http://dusankasan.github.io/Knapsack/
MIT License
535 stars 56 forks source link

Best way to do with return in foreach? #31

Closed roukmoute closed 7 years ago

roukmoute commented 7 years ago

Hi!

I would like to know how can I use pipeline collection with this code:

foreach ($myArrayOfAsciiCode as $ascii) {
    if (strpos($path, chr($ascii))) {
        return true;
    }
}

return false;

I do this:

return !Collection::from(self::INVALID_PATH_ASCII)
                  ->filter(
                      function (string $ascii) use ($path): bool {
                          return strpos($path, chr($ascii));
                      }
                  )
                  ->isEmpty();

Is this the better way?

Thanks

DusanKasan commented 7 years ago

Hi. The some operation does exactly what you need. Let me know if you have further questions.

jdreesen commented 7 years ago

You could use some (the method names in the docs seem to be wrong, though. I'll create a PR to fix this):

Collection::from($myArrayOfAsciiCode)->some(function ($ascii) use ($path) {
   return strpos($path, chr($ascii)) !== false;
});
DusanKasan commented 7 years ago

And I just realized the docs are showing wrong examples. Need to fix asap. Refer to tests for examples for now.

jdreesen commented 7 years ago

Fixed in #32

roukmoute commented 7 years ago

Thanks for your rapidity guys :blush:!