note 99975 deleted from function.array-filter by danbrown
| From: | danbrown@php.net | Date: | Fri, 17 Sep 2010 14:33:05 +0000 |
| Subject: | note 99975 deleted from function.array-filter by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-172680@lists.php.net to get a copy of this message | ||
Note Submitter: sergiy dot sokolenko at gmail dot com
----
>> mchargue at usc dot edu
If you want to pass a parameter to the callback function, there is better way than defining global
variables in PHP 5.3 (also see http://ua.php.net/manual/en/functions.anonymous.php):
<?php
/**
* This function works exactly like array_search,
* but returns an array of all found values.
*/
function array_search_all($needle, array $haystack, $strict = false)
{
return array_filter($haystack, function($value) use ($needle, $strict) {
if ($strict) {
return $value === $needle;
} else {
return $value == $needle;
}
});
}
$haystack = array(
0 => 1,
1 => 2,
2 => 3,
3 => true,
4 => false
);
// Example 1: search for "3"
var_export(array_search_all(3, $haystack));
// prints:
// array (
// 2 => 3,
// 3 => true, ( because 3 == true )
// 5 => true,
// )
// Example 2: search for "3" in strict mode
var_export(array_search_all(3, $haystack, true));
// prints:
// array (
// 2 => 3,
// )