Created
June 19, 2014 05:21
-
-
Save artoodetoo/0379133f2c9fe88407ff to your computer and use it in GitHub Desktop.
PHP: Find value in array using a user-defined comparison function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Искать в массиве с помощью пользовательской функции. | |
* Поиск идет до первого не false результата. | |
* @param mixed $needle что ищем | |
* @param array $haystack где ищем | |
* @param callable $callback функция сравнения | |
* @return mixed false или индекс массива | |
*/ | |
function array_usearch($needle, $haystack, $callback) | |
{ | |
foreach ($haystack as $key => $value) { | |
if (call_user_func($callback, $needle, $value) !== false) { | |
return $key; | |
} | |
} | |
return false; | |
} | |
// поиск подстроки в массиве | |
var_export( | |
array_usearch( | |
'класс', | |
['Одноклассник', 'ПТУшник'], | |
function ($a, $b) { return strpos($b, $a); } | |
) | |
); // 0 | |
// поиск числа, кратного указанному | |
var_export( | |
array_usearch( | |
4, | |
[1, 2, 10, 12, 44], | |
function ($a, $b) { return $b % $a == 0; } | |
) | |
); // 3 | |
// поиск совпадения, при частичном совпадении в $best будет наилучший кандидат | |
$best = ''; | |
var_export( | |
array_usearch( | |
'/profile/essential/change-password', | |
['/profile', '/profile/essential', '/profile/privacy'], | |
function ($a, $b) use(&$best) { | |
if ($a == $b) { | |
$best = $b; | |
return true; | |
} | |
if (strpos($a, $b) === 0 && strlen($b) > strlen($best)) { | |
$best = $b; | |
} | |
return false; | |
} | |
) | |
); // false | |
var_export($best); // '/profile/essential' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment