Search code examples
phparraysconditional-statementsfunctional-programmingfiltering

Separate array values into qualifying and non-qualifying arrays


I'm familiar with array_filter, and I'm trying to think more functional, but I was wondering if there is a way to keep the discarded values? For example, if I had an array like:

$arr = array( 1, 2, 3, 4 );
$arrGreaterThanTwo = array_filter($arr, function($item) {
    return $item > 2;
});

The results would be: array( 3, 4 ).

  1. Is there a way to keep the discarded values array( 1, 2 )?
  2. Or do I need to reuse array_filter again on the original array and return item <= to 2?
  3. If I use array_filter again to grab array( 1, 2 ), wouldn't that be inefficient by looping over the original array twice?

At the end, I'm just trying to loop over once with array_filter and keep the discarded values too into a separate array.


Solution

  • function array_partition(array $array, callable $fn){
        $result = [[],[]];
        foreach ( $array as $value ){
            $result[$fn($value)?0:1][]=$value;
        }
        return $result;
    }
    // example usage:
    $res = array_partition([1,2,3,4,5,6,7,8,9,10], function($i) { return $i&1==1;});
    

    Although this is not functional implementation it has a functional interface just like array_filter.