6

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

2
  • I'm trying to solve it with Arr::where helper, can you show what you have tried and perhaps we can help with what isn't working. Commented Apr 24, 2020 at 14:23
  • php.net/manual/en/function.array-filter.php is your friend Commented Apr 24, 2020 at 14:24

3 Answers 3

25
$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;
    });
Sign up to request clarification or add additional context in comments.

Comments

7

You can use collection where:

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

Comments

6

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);

1 Comment

This non-laravel (general PHP) advice has been given on Stack Overflow many times prior to 2020.

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.