How to filter an array by a condition

后端 未结 7 703
长发绾君心
长发绾君心 2020-11-22 06:12

I have an array like this:

array(\"a\" => 2, \"b\" => 4, \"c\" => 2, \"d\" => 5, \"e\" => 6, \"f\" => 2)

Now I want to fi

7条回答
  •  难免孤独
    2020-11-22 06:58

    I think the snappiest, readable built-in function is: array_intersect()

    Code: (Demo)

    $array = array("a" => 2, "b" => 4, "c" => 2, "d" => 5, "e" => 6, "f" => 2);
    var_export(array_intersect($array, [2]));
    

    Output:

    array (
      'a' => 2,
      'c' => 2,
      'f' => 2,
    )
    

    Just make sure you declare the 2nd parameter as an array because that is the value type expected.

    Now there is nothing wrong with writing out a foreach loop, or using array_filter(), they just have a more verbose syntax.

    array_intersect() is also very easy to extend (include additional "qualifying" values) by adding more values to the 2nd parameter array.

提交回复
热议问题