add to array if it isn't there already

前端 未结 14 1089
北海茫月
北海茫月 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.

    0 讨论(0)
  • 2020-12-13 08:31

    Easy to write, but not the most effective one:

    $array = array_unique(array_merge($array, $array_to_append));
    

    This one is probably faster:

    $array = array_merge($array, array_diff($array_to_append, $array));
    
    0 讨论(0)
  • 2020-12-13 08:31
    if (!in_array($value, $a))
      $a[]=$value;
    
    0 讨论(0)
  • 2020-12-13 08:32

    Try adding as key instead of value:

    Adding an entry

    function addEntry($entry) {
        $this->entries[$entry] = true;
    }
    

    Getting all entries

    function getEntries() {
        return array_keys($this->enties);
    }
    
    0 讨论(0)
  • 2020-12-13 08:35

    You'd have to check each value against in_array:

    $a=array();
    // organize the array by cusip
    foreach($array as $k=>$v){
        foreach($v as $key=>$value){
            if(!in_array($value, $a)){
            $a[]=$value;
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-13 08:36
    if (!in_array(...))  
      array_push(..)
    
    0 讨论(0)
提交回复
热议问题