'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



Solution 1:[1]

You can use collection where:

collect($array)->where('type', 1)->all();

Solution 2:[2]

You can use array_filter and inside give the condition you need.

$data = array_filter($array, function ($item) {
    return $item["type"] === 1;
});

print_r($data);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 TsaiKoga
Solution 2 nas