Skip to content

Instantly share code, notes, and snippets.

@t0yohei
Last active June 8, 2022 02:19
Show Gist options
  • Save t0yohei/db2f696b8c5e8f8c45468884b15fade6 to your computer and use it in GitHub Desktop.
Save t0yohei/db2f696b8c5e8f8c45468884b15fade6 to your computer and use it in GitHub Desktop.
array find(detect) in ruby to PHP
/**
* @param array $array
* @param callable $function
* @return null | array
*/
function array_find(array $array, callable $function)
{
$result = array_filter(
$array,
function ($item) use ($function) {
return $function($item);
}
);
if (count($result) == 0) return null;
return array_values($result)[0];
}
#
## usage
#
# $items = ['ab', 'c', 'de', 'fgh'];
# $result_item = array_find($items, function ($item) {
# return strlen($item) == 2;
# });
#
# print_r($result_item); # ab
#
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment