Click here to Skip to main content
15,892,005 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
how to remove duplicates from the salad list?

What I have tried:

<pre>$veggies = array("Potato", "Cucumber", "Carrot", "Orange", "Green Beans", "Onion");
            $fruits  = array("Apple", "Banana", "Orange", "Pineapple", "Grapes", "Watermelon");
            $salad = array_unique(array_merge($veggies ,$fruits));
            print_r($salad);
Posted
Updated 3-Apr-18 1:33am
Comments
Maciej Los 3-Apr-18 7:12am    
According to the documentation, an array_unique[^] method returns a new array without duplicate values. What do you need? What's wrong with your code?

Please, see my comment to the question...

According to the documentation, an array_unique[^] method returns a new array without duplicate values.
 
Share this answer
 
Your code already filters out all duplicates. If you would like case-insensitivity you can use this function
PHP
function array_iunique($array) {
    return array_intersect_key(
        $array,
        array_unique(array_map("StrToLower",$array))
    );
}
(Found this gem on Stackoverflow[^].)
Use this function in your code and change the "Orange" in the $veggies to "orange".
PHP
$veggies = array("Potato", "Cucumber", "Carrot", "orange", "Green Beans", "Onion");
$fruits  = array("Apple", "Banana", "Orange", "Pineapple", "Grapes", "Watermelon");
$salad = array_iunique(array_merge($veggies ,$fruits));
print_r($salad);
This outputs to
Array
(
    [0] => Potato
    [1] => Cucumber
    [2] => Carrot
    [3] => orange
    [4] => Green Beans
    [5] => Onion
    [6] => Apple
    [7] => Banana
    [9] => Pineapple
    [10] => Grapes
    [11] => Watermelon
)
The Orange appears only once in the result.
 
Share this answer
 
v2
Comments
1234Amit 3-Apr-18 7:37am    
sir if in the fruit list if i change Orange from orange (i have used small "o") its not giving me the output,
Christiaan van Bergen 3-Apr-18 7:50am    
I updated my answer.
1234Amit 3-Apr-18 7:57am    
sir can you edit my code and tel me because im unable to use the function which u have told
Christiaan van Bergen 3-Apr-18 7:58am    
Put the function in your code file, and change this line:
$salad = array_iunique(array_merge($veggies ,$fruits));
It is now using 'array_iunique' instead of 'array_unique'.
1234Amit 3-Apr-18 8:06am    
thanks a lot sir it got fixed.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900