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 ).
At the end, I'm just trying to loop over once with array_filter and keep the discarded values too into a separate array.
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
.