Skip to content

Instantly share code, notes, and snippets.

@krtek4
Last active February 11, 2021 15:09
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save krtek4/0bb3aefd58106e254bd2 to your computer and use it in GitHub Desktop.
Save krtek4/0bb3aefd58106e254bd2 to your computer and use it in GitHub Desktop.
Functional programming techniques in PHP
<?php
// Return the first / last element matching a predicate
function first(array $array, $test) {
foreach($array as $v)
if($test($v))
return $v;
return null;
}
// Return true if at least one element matches the predicate
function any($array, $test) {
foreach($array as $v)
if($test($v))
return true;
return false;
}
// Return true if all elements match the predicate
function all($array, $test) {
foreach($array as $v)
if(! $test($v))
return false;
return true;
}
function last(array $array, $test) {
return first(array_reverse($array), $test);
}
// Compose two functions together
function compose($f, $g) {
return function() use($f,$g) {
return $f(call_user_func_array($g, func_get_args()));
};
}
@vkalinsky
Copy link

Semicolon in line 28?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment