Dan array. Remove from the array all elements that occur more than 2 times. Delete the elements, but instead of them (deleted elements) appear zeros, how to get rid of them?

$arr=[5,0,5,9,-3,4,0,5,6,7,8,-9,0]; $count = 0; $n=count($arr); for ( $i = 0; $i < $n; $i++) { for ( $j = 0; $j < $n; $j++) { if($arr[$i] == $arr[$j]) { $count++; $a=$j; } } if($count >= 2) { for ($j = $a; $j < $n-1; $j++) { $arr[$j] = $arr[$j+1]; } $n--; for ($j = $i; $j < count($arr)-1; $j++) { $arr[$j] = $arr[$j+1]; } $arr--; } $count = 0; } for ( $i = 0; $i < count($arr); $i++) { echo $arr[$i]." "; } 
  • in the sample, no element is found three or more times, like - splash58
  • @ splash58, you're wrong - pompidu312123131
  • I'm not mistaken, straighten the heading for не менее - splash58
  • @ splash58, at least 2 times or more than 2 times, the same thing - pompidu312123131
  • более 2 раз - 2 not included :) - splash58

2 answers 2

I would do something like this. Only keys will not be consistent.

 $arr=[-1,0,5,9,-3,4,5,6,7,8,-9,0]; $count = 0; $n=count($arr); $a = array(); for ( $i = 0; $i < $n; $i++) for ( $j = 0; $j < $n; $j++) if($arr[$i] == $arr[$j]) $a[$i][] = $j; foreach($a as $item) if(count($item) >= 2) foreach($item as $key) if (isset($arr[$key])) unset($arr[$key]); echo implode(' ', $arr)."\n"; 
  • , thanks for the help - pompidu312123131
  • yes not for that :) - splash58
  • php, gives out a bunch of Notice: Undefined offset: - pompidu312123131
  • This is probably necessary to rearrange the cycles $a = array(); . I do not have opportunity to start pkhp - splash58
  • eva.in does not write warnings. or i don't know how. tell what happened - splash58

Why reinvent the wheel?
There is already a ready solution.
Here is

  • I know about this function, I need to fix my bike is simple;) - pompidu312123131
  • Do not create answer-links. It is better to bring out some information in the answer itself and add a link at the end. Otherwise, if the site is unavailable, the link along with the answer will no longer be relevant - Timofei Bondarev