Search needle in_array using a user-defined comparison function

十年热恋 提交于 2020-01-25 06:13:49

问题


After searching some question on SO about this issue I could only found this and this but both do not allow sending argument (AKA needle) to the search function but using pre-defined function and using array_filter.

I search in_array documentation but found none.

I want to have something like (as usort enable):

function uin_array($haystack, $needle, $compareFunc)

I manage to implement it with simple foreach loop:

function uin_array($haystack, $needle, $compareFunc) {
    foreach($haystack as $e) {
        if ($compareFunc($needle, $e) == 0)
            return true;
    }    
    return false;
}

Example:

$found = uin_array(["AA", "BB", "CC", "DD"], "cc", "strcasecmp");

This could also be used in searching in the multi-dimension array.

My question:

Is there any built-in function/flag like this in PHP that I'm not aware of? Is there any better way to implement it?

Edit:

I know I can use array_filter as: current(array_filter($haystack, function($element) use ($needle) { ... })) but that is O(n) in all cases - using loop and break or in_array may be O(1) in some case (will be O(n) in only in worst case but not all)


回答1:


Take a look at a great nikic/iter library.

$haystack = ["AA", "BB", "CC", "DD"];
$needle = "cc";

$found = \iter\any(function ($value) use ($needle) {
    return strcasecmp($needle, $value);
}, $haystack);



回答2:


If you are not afraid of function currying, take a look at functional-php library.

use function Functional\partial_any;
use function Functional\some;
use function Functional\placeholder;

$haystack = ["AA", "BB", "CC", "DD"];
$needle = "cc";
$compareFunc = "strcasecmp";

$found = some($haystack, partial_any($compareFunc, $needle, placeholder()));

The library provides nice helpers to write code in more functional style, but I would advice you to use it in the whole project or not to use it at all, because requiring it only for one or two occasional uses doesn't make a lot of sense.




回答3:


For this purpose, you can user either array_reduce or array_filter to return 0, 1 or more items that will match your criteria.




回答4:


You can use array_map, strcasecamp, array_filter

$needle      = 'cc';
$compareFunc = 'strcasecmp';
$found    = count(array_filter(array_map(function($v) use ($needle,$compareFunc){
  if($compareFunc($v, $needle) == 0) return 1;
}, ["AA", "BB", "CC", "DD"])));


来源:https://stackoverflow.com/questions/55797796/search-needle-in-array-using-a-user-defined-comparison-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!