add to array if it isn't there already

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

    You should use the PHP function in_array (see http://php.net/manual/en/function.in-array.php).

    if (!in_array($value, $array))
    {
        $array[] = $value; 
    }
    

    This is what the documentation says about in_array:

    Returns TRUE if needle is found in the array, FALSE otherwise.

提交回复
热议问题