Elegant way to search an PHP array using a user-defined function

后端 未结 6 1445
感情败类
感情败类 2020-12-06 03:58

Basically, I want to be able to get the functionality of C++\'s find_if(), Smalltalk\'s detect: etc.:

// would return the element o         


        
6条回答
  •  暖寄归人
    2020-12-06 04:44

    The original array_search returns the key of the matched value, and not the value itself (this might be useful if you're will to change the original array later).

    try this function (it also works will associatives arrays)

    function array_search_func(array $arr, $func)
    {
        foreach ($arr as $key => $v)
            if ($func($v))
                return $key;
    
        return false;
    }
    

提交回复
热议问题