1

I am trying to remove duplicates from an array. As you can see below, the resulting list from the code contains two incidents of Sugar and Coffee. What can I do to effectively remove the duplicates from the list? (The code for this is actually much longer, and includes over 400 elements).

<?php    
     $FoodList = array();
     $zb = Milk
     $cd = Bread
     $dc = Orange
     $ce = Apple
     $ec = KiwiFruit
     $cg = GrapeFruit
     $gc = Cucumber
     $ch = Biscuit
     $hc = Caramel
     $dv = Juice
     $ci = SoftDrink
     $ic = Banana
     $cj = Tea
     $cl = Sugar
     $jc = Coffee 
     $ck = Yoghurt
     $kc = Pizza Base
     $lc = Tuna

     if ($_POST['Dairy'] == 'Yes') { //Radio check box
         array_push($FoodList, $zb, $cd, $dc, $ce, $ec);
     }
     if ($_POST['GlutenFree'] == 'Yes') {
         array_push($FoodList, $cg, $gc, $ch, $hc, $dv);
     }
     if ($_POST['Fruit'] == 'Yes') {
         array_push($FoodList, $ci, $ic, $cj, $jc, $cl);
     }
     if ($_POST['Sweets'] == 'Yes') {
         array_push($FoodList, $jc, $ck, $kc, $cl, $lc);    
     }
     foreach ( $FoodList as $key => $value ) {
         echo "<li>" . $value . "</li>";
     }
     echo "</ul>";
}
?>

Thankyou so much

2 Answers 2

5

Use array_unique function to remove duplicate values from an array.

Sign up to request clarification or add additional context in comments.

Comments

3

Try this,

$FoodList=array_unique($FoodList);
if(!empty($FoodList))
{
    $str="<ul>";
    foreach ($FoodList as $key => $value)
    {
       $str.="<li>" . $value . "</li>";
    }
    $str.= "</ul>";
    echo $str;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.