Reading this article got me to thinking…
Since PHP also has closures this should be doable in it as well.
$wordHasChar = function($word, $char) {
return stripos($word, $char) !== FALSE;
};
$wordStartsWithChar = function($word, $char) {
return stripos($word, $char) === 0;
}
$findWords = function( $char, $string, $condition ) {
return array_filter(explode(' ', $string), function($e) use ($char, $condition) {
return $condition($e, $char);
} );
};
Granted, the above is rather contrived and there are better ways to go about the process given. The idea of passing a function as an argument in PHP hadn’t occurred to me despite the fact I do it all the time in Javascript. I think a major limiting factor is going to be PHP’s need of the use statement in closures, but I could be wrong. Anyway, continuing the above, if you wanted all members of a db return array containing a letter A starting a word…
$char = 'A';
$hasA = array_filter($data, function($e) use ($char, $findWords, $wordStartsWithChar) {
return $findWords($char, $e, $wordStartsWith);
});
On one hand it feels like it could be nifty. On the other, bizarre. Thoughts?
EDIT: None of the above code tested - I’m just musing out some thoughts.