1

I have this array:

$arr_to_filter = array(1, 3, 5, 7, 10, 12, 15);
$filter = array(0, 1, 1, 0, 1);

Expected result:

Array ( 
       [0] => 3 
       [1] => 5 
       [2] => 10 
)

I can achieve this by this loop:

$arr_to_filter = array(1, 3, 5, 7, 10, 12, 15);
$filter = array(0, 1, 1, 0, 1);
$output_array = array();

foreach($arr_to_filter as $key=>$val) {
   if(isset($filter[$key]) && $filter[$key]) {
       $output_array[] = $val;
   }
}

print_r($output_array);

Can i achieve this using built in functions like array_filter or another built in function without using loops?

1
  • "Built in functions like array_***" are made with loops. Commented May 24, 2017 at 20:52

2 Answers 2

3

If you're using PHP >= 5.6, you can take advantage of array_filter()'s third argument, allowing you to match keys with your filter set:

$arr_to_filter = array(1, 3, 5, 7, 10, 12, 15);
$filter = array(0, 1, 1, 0, 1);

$result = array_filter(
    $arr_to_filter,
    function($key) use ($filter) {
        return !empty($filter[$key]);
    },
    ARRAY_FILTER_USE_KEY
);

var_dump($result);

If you're using an earlier version of PHP, then you need to filter on the keys, and intersect that result against your original array:

$result = array_intersect_key(
    $arr_to_filter,
    array_filter(
        array_keys($arr_to_filter),
        function($key) use ($filter) {
            return !empty($filter[$key]);
        }
    )
);

If you want to reset the keys after either of these methods, then just use array_values()

Sign up to request clarification or add additional context in comments.

Comments

1

The solution using array_map, array_slice and array_reduce functions:

$filtered = array_reduce(array_map(null, array_slice($arr_to_filter, 0, count($filter)), $filter),
    function($r, $a){
        if ($a[1]) $r[] = $a[0];
        return $r;
    }, []);

print_r($filtered);

The output:

Array
(
    [0] => 3
    [1] => 5
    [2] => 10
)

1 Comment

@semsem, actually, your foreach loop approach is not so bad in such case

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.