add to array if it isn't there already

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

    If you don't care about the ordering of the keys, you could do the following:

    $array = YOUR_ARRAY
    $unique = array();
    foreach ($array as $a) {
        $unique[$a] = $a;
    }
    
    0 讨论(0)
  • 2020-12-13 08:55

    you can try using "in_array":

    function insert_value($value, &$_arr) {
        if (!in_array($value, $_arr)) {
            $_arr[] = $value;
        }
    }
    
    0 讨论(0)
提交回复
热议问题