Skip to content

Instantly share code, notes, and snippets.

@pgchamberlin
Last active August 29, 2015 13:57
Show Gist options
  • Save pgchamberlin/9619843 to your computer and use it in GitHub Desktop.
Save pgchamberlin/9619843 to your computer and use it in GitHub Desktop.
Functional vs procedural loops in PHP
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