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

Marc picture Marc · Apr 10, 2012 · Viewed 92.9k times · Source

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 value is already in the array? Hope I am clear. Thank you in advance.

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

Answer

Rocket Hazmat picture Rocket Hazmat · Apr 10, 2012

You check if it's there, using in_array, before pushing.

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

The ,true enables "strict checking". This compares elements using === instead of ==.