<?php
$array = [
'a' => 'dog',
'b' => 'cat',
'c' => 'cow',
'd' => 'duck',
'e' => 'goose',
'f' => 'elephant'
];
// Find the first animal with a name longer than 4 characters.
var_dump(array_find($array, function (string $value) {
return strlen($value) > 4;
}));
// Find the first animal whose name begins with f.
var_dump(array_find($array, function (string $value) {
return str_starts_with($value, 'f');
}));
// Find the first animal where the array key is the first symbol of the animal.
var_dump(array_find($array, function (string $value, $key) {
return $value[0] === $key;
}));
// Find the first animal where the array key matching a RegEx.
var_dump(array_find($array, function ($value, $key) {
return preg_match('/^([a-f])$/', $key);
}));
?>
Das oben gezeigte Beispiel erzeugt folgende Ausgabe:
string(5) "goose"
NULL
string(3) "cow"
string(3) "dog"