[FIXED] Push only unique values into an array while looping

Issue

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

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

Solution

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 ==.

Answered By – gen_Eric

Answer Checked By – Senaida (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published