DusanKasan / Knapsack

Collection pipeline library for PHP

Home Page:http://dusankasan.github.io/Knapsack/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Best way to do with return in foreach?

roukmoute opened this issue · comments

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

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

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;
});

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

Fixed in #32

Thanks for your rapidity guys 😊!