Return all array elements except for a given key

后端 未结 7 1337
暖寄归人
暖寄归人 2021-02-02 09:06

Simple one, I was just wondering if there is a clean and eloquent way of returning all values from an associative array that do not match a given key(s)?

$array          


        
7条回答
  •  执念已碎
    2021-02-02 09:34

    There have been a few discussions about speed when using in_array. From what I've read, including this comment1, using isset is faster than in_array.

    In that case your code would be:

    function arrayExclude($array, array $excludeKeys){
    
        $return = [];
    
        foreach($array as $key => $value){
            if(!isset($excludeKeys[$key])){
                $return[$key] = $value;
            }
        }
        return $return;
    }
    

    That would be slightly faster, and may help in the event that you're needing to process large datasets.

提交回复
热议问题