php array_push() -> How not to push if the array already contains the value

前端 未结 9 1881
无人共我
无人共我 2020-12-29 01:04

I am using the following loop to add items to an an array of mine called $liste. I would like to know if it is possible somehow not to add $value to the $liste array if the

相关标签:
9条回答
  • 2020-12-29 01:55

    maybe you want to use it as an associative array instead. it's implemented as (something like) a hash table, so you get constant insert time instead of linear.

    function find_uniq( $something ) {
        foreach($something as $value){
             $liste[$value]++;
        }
        return array_keys( $liste );
    }
    
    0 讨论(0)
  • 2020-12-29 01:58

    You can simply check this condition before calling array_push(). Use array_search() and use a strong comparison to false to see if the value is present:

    foreach( $something as $value ){
        if( array_search( $value, $liste, true ) === false ){
            array_push( $liste, $value );
        }
    }
    

    (By the way: Add ,true to array_search to use "strict checking". This will use === for comparisons instead of ==)

    0 讨论(0)
  • 2020-12-29 02:02

    Great answers are already present above, but if you have multiple array_push() all over your code, it would be a pain to write if(in_array()) statements every time.

    Here's a solution that will shorten your code for that case: Use a separate function.

    function arr_inserter($arr,$add){ //to prevent duplicate when inserting
        if(!in_array($add,$arr))
            array_push($arr,$add);
        return $arr;
    }
    

    Then in all your array_push() needs, you can call that function above, like this:

    $liste = array();
    foreach($something as $value){
        $liste = arr_inserter($liste, $value);
    }
    

    If $value is already present, $liste remains untouched.

    If $value is not yet present, it is added to $liste.

    Hope that helps.

    0 讨论(0)
提交回复
热议问题