0

duplicate items in an array in sort of duplicated

hi friends, i have an input like this: i wrote this code to print for me duplicated items but in order of duplicated. right answer is "lemon, apple" but my code prints "apple,lemon". would you help me to find my mistake? <?php $n = 6; $names= ["apple", "lemon", "lemon", "apple", "kiwi", "orange"]; $new_array = []; for ($i=0; $i <$n ; $i++) { for ($s=0; $s <$n ; $s++) { if ( $names[$i] == $names[$s] && $i!=$s ) { $new_array[] = $names[$i]; //print_r ($names[$i]); } } } //print_r($new_array); $m = count($new_array); $a = []; for ($j=0; $j <$m ; $j++) { if (!in_array($new_array[$j],$a)){ $a[] = $new_array[$j]; } } print_r ($a);

18th Jun 2020, 7:08 AM
Neda
1 Antwort
0
The reason is because apple is at$name[0] and iteration must be done for apple before it goes to $name[1] which is lemon. Therefore apple duplicate will be caught before lemon's.
18th Jun 2020, 4:49 PM
MILES CODER
MILES CODER - avatar