array ( 0 => 'index.php', 1 => 'PHP Manual', ), 'head' => array ( 0 => 'UTF-8', 1 => 'zh', ), 'this' => array ( 0 => 'function.array-find-key.php', 1 => 'array_find_key', 2 => 'Returns the key of the first element satisfying a callback function', ), 'up' => array ( 0 => 'ref.array.php', 1 => '数组 函数', ), 'prev' => array ( 0 => 'function.array-find.php', 1 => 'array_find', ), 'next' => array ( 0 => 'function.array-flip.php', 1 => 'array_flip', ), 'alternatives' => array ( ), 'source' => array ( 'lang' => 'en', 'path' => 'reference/array/functions/array-find-key.xml', ), 'history' => array ( ), ); $setup["toc"] = $TOC; $setup["toc_deprecated"] = $TOC_DEPRECATED; $setup["parents"] = $PARENTS; manual_setup($setup); contributors($setup); ?>
(PHP 8 >= 8.4.0)
array_find_key — Returns the key of the first element satisfying a callback function
array_find_key() returns the key of the first element of an
array for which the given callback
returns true
.
If no matching element is found the function returns null
.
The function returns the key of the first element for which the
callback
returns true
. If no matching element is
found the function returns null
.
示例 #1 array_find_key() example
<?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_key($array, function (string $value) {
return strlen($value) > 4;
}));
// Find the first animal whose name begins with f.
var_dump(array_find_key($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_key($array, function (string $value, $key) {
return $value[0] === $key;
}));
// Find the first animal where the array key matching a RegEx.
var_dump(array_find_key($array, function ($value, $key) {
return preg_match('/^([a-f])$/', $key);
}));
?>
以上示例会输出:
string(1) "e" NULL string(1) "c" string(1) "a"