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

后端 未结 6 1443
感情败类
感情败类 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:42

    Use \iter\search() from nikic's iter library of primitive iteration functions. It has the added benefit that it operates on both arrays and Traversable collections.

    $foundItem = \iter\search(function ($item) {
        return $item > 10;
    }, range(1, 20));
    
    if ($foundItem !== null) {
        echo $foundItem; // 11
    }
    

提交回复
热议问题