-
-
Save krtek4/0bb3aefd58106e254bd2 to your computer and use it in GitHub Desktop.
Functional programming techniques 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
<?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())); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Semicolon in line 28?