How to filter an array by a condition

后端 未结 7 683
长发绾君心
长发绾君心 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:52

    You can iterate on the copies of the keys to be able to use unset() in the loop:

    foreach (array_keys($array) as $key) {
        if ($array[$key] != 2)  {
            unset($array[$key]);
        }
    }
    

    The advantage of this method is memory efficiency if your array contains big values - they are not duplicated.

    EDIT I just noticed, that you actually only need the keys that have a value of 2 (you already know the value):

    $keys = array();
    foreach ($array as $key => $value) {
        if ($value == 2)  {
            $keys[] = $key;
        }
    }
    

提交回复
热议问题