Home remove duplicate arrays in loop
Reply: 5

remove duplicate arrays in loop

Paul Dessert
1#
Paul Dessert Published in 2018-02-13 07:33:13Z

I have an associative array that might contain duplicates. I am trying to loop through the array and compare the current element with the next element in the array. If there is a duplicate, it should be removed.

The code below removes one instance of the element. In the test array I'm using, I have 3 duplicate part numbers, but my code only removes one. I'm left with two. I only want one to remain.

  $length = count($items);

   for($i = 0; $i < $length -1; $i++){
    if($items[$i]['part_number'] == $items[$i+1]['part_number']){
      unset($items[$i+1]);
      $items = array_values($items);
    }
   }

What am I doing wrong here?

bumperbox
2#
bumperbox Reply to 2018-02-13 07:50:58Z

You need to loop backwards through the array, and delete the current item.

$length = count($items);

for($i = $length - 1; $i > 0; $i--){
    if($items[$i]['part_number'] == $items[$i-1]['part_number']){
        unset($items[$i]);
    }
}
hoyeonUm
3#
hoyeonUm Reply to 2018-02-13 07:45:03Z

becuase your code is The $ items value is in the for statement.

if you want unique array, you have to array_unique function

http://php.net/manual/en/function.array-unique.php

Shobi P P
4#
Shobi P P Reply to 2018-02-13 08:18:43Z

One dirty hack is to check again if you have a duplicate by decreasing $i.

for($i = 0; $i < $length -1; $i++){
    if($items[$i]['part_number'] == $items[$i+1]['part_number']){
        unset($items[$i+1]);
        $items = array_values($items);
        $i--;
    }
}

This way it will again test your previous value against next item in array.
So if 0==1, then next time if 0==2.
Your code did 0==1 then (2)==(3).

vpalade
5#
vpalade Reply to 2018-02-13 08:00:20Z

In your case after you unset element, $i++ in for loop, you reindexed your array and you skip one element. Add $i-- if you unset item. Or you can reindex your array after for loop.

Fil
6#
Fil Reply to 2018-02-13 08:00:43Z

This is also a very simple example you can start improving with.

<?php
$test = ['sample', 'sample', 'sample', 'not', 'not', 'no', 'no'];
$test2 = [];

$k = 0;
foreach ($test as $key => $value) {
  if ($key == 0) {
    $test2[$k] = $value;
    $k++;
  } else {
    if ($test2[$k - 1] != $value) {
      $test2[$k] = $value;
      $k++;
    }
  }
}

$test = $test2;

var_dump($test);
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.366356 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO