add to array if it isn't there already

前端 未结 14 1314
北海茫月
北海茫月 2020-12-13 07:53

How do I add elements to an array only if they aren\'t in there already? I have the following:

$a=array();
// organize the array
foreach($array as $k=>$v)         


        
14条回答
  •  没有蜡笔的小新
    2020-12-13 08:40

    Since you seem to only have scalar values an PHP’s array is rather a hash map, you could use the value as key to avoid duplicates and associate the $k keys to them to be able to get the original values:

    $keys = array();
    foreach ($array as $k => $v){
        if (isset($v['key'])) {
            $keys[$value] = $k;
        }
    }
    

    Then you just need to iterate it to get the original values:

    $unique = array();
    foreach ($keys as $key) {
        $unique[] = $array[$key]['key'];
    }
    

    This is probably not the most obvious and most comprehensive approach but it is very efficient as it is in O(n).

    Using in_array instead like others suggested is probably more intuitive. But you would end up with an algorithm in O(n2) (in_array is in O(n)) that is not applicable. Even pushing all values in the array and using array_unique on it would be better than in_array (array_unique sorts the values in O(n·log n) and then removes successive duplicates).

提交回复
热议问题