add to array if it isn't there already

前端 未结 14 1313
北海茫月
北海茫月 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:36

    With array_flip() it could look like this:

    $flipped = array_flip($opts);
    $flipped[$newValue] = 1;
    $opts = array_keys($flipped);
    

    With array_unique() - like this:

    $opts[] = $newValue;
    $opts = array_values(array_unique($opts));
    

    Notice that array_values(...) — you need it if you're exporting array to JavaScript in JSON form. array_unique() alone would simply unset duplicate keys, without rebuilding the remaining elements'. So, after converting to JSON this would produce object, instead of array.

    >>> json_encode(array_unique(['a','b','b','c']))
    => "{"0":"a","1":"b","3":"c"}"
    
    >>> json_encode(array_values(array_unique(['a','b','b','c'])))
    => "["a","b","c"]"
    

提交回复
热议问题