0

I have an array which is 2D and I want to remove duplicates from it,

the var dump look like this 1=>abc.com. 2=>acc.com, 3=>abc.com so I want to remove the second occurence of abc.com, that is I want to remove 3=>abc.com,

I tried to use the nested loop, but the code is not working.

 foreach ($var as $m)
   {
        foreach ($var as $s)
        {
                if(isset($m['Email'])){
                    if($m['Email'] == $s['Email']){
                    echo 'matched with '.$s['Email'];
                    echo '</br>';
                    unset($s);
                    //echo $v['Email'];
                    //echo "<br>";
                }
            }
        }
   }

Am I missing something?

user3680538
  • 65
  • 1
  • 6

3 Answers3

2

You can just use the array_unique function

Edit: Here is the code and output from Here (Codepad)

PHP

<?php
$input = array("1" => "abc.com", "2" => "acc.com", "3" => "abc.com");
$result = array_unique($input);
print_r($result);
?>

Output

Array
(
    [1] => abc.com
    [2] => acc.com
)

Edit2: To have it remove duplicates from a specific column, just use

$output = array_intersect_key($input, array_unique(array_column($input, 'Email')));

Where $input is the complete array and 'Email' is the column you wish to remove duplicates from

Bijan
  • 7,737
  • 18
  • 89
  • 149
  • I just pasted a small snippet of my array, Actually my array consists of more than this, like Email, Id, contact number, etc, I just want to check duplicate on email, so I cant use this function – user3680538 Jul 25 '14 at 23:36
  • Then you are looking for something that is in http://stackoverflow.com/questions/19219362/remove-duplicate-in-array-based-on-column-value – Bijan Jul 25 '14 at 23:39
  • Your code will just be: $output = array_intersect_key($input, array_unique(array_column($input, 'Email'))); – Bijan Jul 25 '14 at 23:40
  • thanks, it says call to undefined function, what is $item and $result in other example? – user3680538 Jul 25 '14 at 23:46
1

array_unique($array);

you also have a mistake in your nested foreach. Assuming what you posted above, you only need one foreach loop. If you need to add a 2nd, it should be based on the temp variables you are setting e.g. foreach($table as $row => $key) .. you can do foreach($key as $item)

etc!

David
  • 5,897
  • 3
  • 24
  • 43
1

If you only want to remove the duplicates you can use array_unique,

$arr = array(
    1 => "abc.com", 
    2 => "acc.com", 
    3 => "abc.com"
); 

$result = array_unique($arr);
print_r($result);
Erlesand
  • 1,525
  • 12
  • 16