Last active
August 29, 2015 13:57
-
-
Save pgchamberlin/9619843 to your computer and use it in GitHub Desktop.
Functional vs procedural loops in PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class someclass | |
{ | |
private $items; | |
function filterItemsUsingForeach() | |
{ | |
$criterion = 'somevalue'; | |
$items = array(); | |
foreach ($this->items as $item) { | |
if (method_exists($item, 'someMethod') && $item->someMethod() == $criterion) { | |
$items[] = $item; | |
} | |
} | |
return $items; | |
} | |
function filterItemsUsingArrayFilter() | |
{ | |
$criterion = 'somevalue'; | |
$items = array_filter( | |
$this->items, | |
function ($item) use ($criterion) { | |
return method_exists($item, 'someMethod') && $item->someMethod() == $criterion; | |
} | |
); | |
return array_values($items); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment