PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, February 13, 2022

[FIXED] Laravel filter array based on element value

 February 13, 2022     laravel, laravel-5, php     No comments   

Issue

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

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


Answered By - pr1nc3
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing