How to Filter in a PHP Array? [closed]

-1

I have a Array of which I need to filter, I am using array_filter the following way:

<?php

$arr = ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4];

var_dump(array_filter($arr, function($v, $k) {
    return $k == 'b' || $v == 4;
  }, ARRAY_FILTER_USE_BOTH));
?>

Effectively it works and returns the filtered result that is the index b and index d , but to me what I would like it to be filtered more precisely if the index b is Value 2 .

Try as follows:

<?php

    $arr = ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4];

    var_dump(array_filter($arr, function($v, $k) {
        return $k == 'b' && $v == 4;
      }, ARRAY_FILTER_USE_BOTH));
    ?>

But it does not return any value to me.

    
asked by Andrés 03.04.2018 в 21:37
source

1 answer

1

According to your code, you will only return the arrays whose index is 'b' and its value is 4, something contradictory to what you have in the array you filter because the element that exists with the index 'b' has a value of 2. Therefore you should change your condition in the return of the array_filter

Before you had:

return $k == 'b' && $v == 4;

Now it should be:

return $k == 'b' && $v == 2;
    
answered by 03.04.2018 / 22:47
source