note 128756 added to function.array-search
| From: | ssilvio at libero dot it | Date: | Sun, 23 Jul 2023 20:21:14 +0000 |
| Subject: | note 128756 added to function.array-search | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-220717@lists.php.net to get a copy of this message | ||
This is my own array_find function.
It accept a Closure function for evaluating if the target element is found.
The Closer function accept index and value of each element of the array, and must return a boolean
value (true if found).
<?php
function array_find(array $array, \Closure $func) {
$ret = null;
if(is_callable($func)) {
foreach($array as $key=>$value) {
$exit = \call_user_func($func, $key, $value);
if ($exit) {
$ret = $value;
break;
}
}
}
return $ret;
}
$obj_1 = new StdClass();
$obj_1->root = 51;
$obj_2 = new StdClass();
$obj_2->root = 52;
$myArray = ["elem_1" => $obj_1, "elem_2" => $obj_2];
$targetRoot = 52;
$objectFound = array_find($myArray, function($idx, $obj) use ($targetRoot) {
return $obj->root == $targetRoot;
});
echo (print_r($objectFound, true));
?>
Output:
stdClass Object
(
[root] => 52
)
----
Server IP: 45.112.84.4
Probable Submitter: 45.91.159.168 (proxied: 2.237.201.22)
----
Manual Page -- https://php.net/manual/en/function.array-search.php
Edit -- https://main.php.net/note/edit/128756
Del: integrated -- https://main.php.net/note/delete/128756/integrated
Del: useless -- https://main.php.net/note/delete/128756/useless
Del: bad code -- https://main.php.net/note/delete/128756/bad+code
Del: spam -- https://main.php.net/note/delete/128756/spam
Del: non-english -- https://main.php.net/note/delete/128756/non-english
Del: in docs -- https://main.php.net/note/delete/128756/in+docs
Del: other reasons-- https://main.php.net/note/delete/128756
Reject -- https://main.php.net/note/reject/128756
Search -- https://main.php.net/manage/user-notes.php