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

前端 未结 9 1938
无人共我
无人共我 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:52

    Two options really.

    Option 1: Check for each item and don't push if the item is there. Basically what you're asking for:

    foreach($something as $value) {
        if( !in_array($value,$liste)) array_push($liste,$value);
    }
    

    Option 2: Add them anyway and strip duplicates after:

    foreach($something as $value) {
        array_push($liste,$value);
    }
    $liste = array_unique($liste);
    

    By the look of it though, you may just be looking for $liste = array_unique($something);.

提交回复
热议问题