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

前端 未结 9 1958
无人共我
无人共我 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 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.

提交回复
热议问题