Skip to content
Advertisement

Laravel filter array based on element value

I have the following array that I need to filter it and get just the elements which have type = 1

array:5 [
  0 => array:3 [
    "id" => 1
    "name" => "Agua Corriente"
    "type" => 1
  ]
  1 => array:3 [
    "id" => 2
    "name" => "Cloaca"
    "type" => 1
  ]
  2 => array:3 [
    "id" => 3
    "name" => "Gas Natural"
    "type" => 2
  ]
  3 => array:3 [
    "id" => 4
    "name" => "Internet"
    "type" => 3
  ]
  4 => array:3 [
    "id" => 5
    "name" => "Electricidad"
    "type" => 3
  ]
]

This is the expected result:

array:2 [
  0 => array:3 [
    "id" => 1
    "name" => "Agua Corriente"
    "type" => 1
  ]
  1 => array:3 [
    "id" => 2
    "name" => "Cloaca"
    "type" => 1
  ]
]

I’m trying to solve it with Arr::where helper but I’m not getting the expected result. Does anyone can help me?

Regards

Advertisement

Answer

$filteredArray = Arr::where($myArray, function ($value, $key) {
    return $value['type'] == 1;
});

This is how you can use Arr::where in your array, and should work fine.

Also for things like this laravel collections have really handy tools, you should have a look at it as well.

If you want to filter based on a dynamically assigned variable, which most of the times is the case you can simply inject it in your nested function like:

    $type = 1;
    $filteredArray = Arr::where($myArray, function ($value, $key) use($type) {
        return $value['type'] == $type;
    });
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement