1

How can I delete duplicates from multiple arrays?

pinky and cocos are double in my array. All words which are double, must be removed. If those are removed, I will put these words in my select. I get those words from my database.

The query:

$queryClient = " SELECT DISTINCT `clients` FROM `reps` WHERE `clients` != ''";

This is my code:

while($row =  mysql_fetch_assoc($resultClient)){
    $names = explode(",", $row['clients']);
    echo '<pre>'; print_r($names); echo '</pre>';
}

Result: (Those food words are just an example)

Array
    (
        [0] => chocolate
    )
    Array
    (
        [0] => vanilla
        [0] => cocos
    )
    Array
    (
        [0] => strawberry
    )
    Array
    (
        [0] => pinky
        [1] => watermelon
        [2] => melon
        [3] => cocos
    )
    Array
    (
        [0] => pinky 
    )
    Array
    (
        [0] => dark-chocolate
    )

I tried this in my while loop but it did not work:

$array = array_unique($names, SORT_REGULAR);

How can I remove all duplicates? Can you help me or do you have a solution for my problem? Help.

7
  • What is the desired result? Commented Oct 24, 2017 at 12:09
  • i want a selector. the options of that selector is foods from my db but those wont be double Commented Oct 24, 2017 at 12:11
  • Sorry, already did, I deleted my comment ;) Commented Oct 24, 2017 at 12:14
  • So you also need to flatten the array? Commented Oct 24, 2017 at 12:15
  • Ps. this will probably be alot easier and cleaner to solve with a SQL query, so if you post that we can give you some pointers ;) Check out GROUP BY and the function group_concat(DISTINCT field_name) and similar :) Commented Oct 24, 2017 at 12:20

3 Answers 3

4

Here's a one-liner:

print_r(array_unique(call_user_func_array('array_merge', $names)));

First merge all subarrays into one, then get unique values.

Full example:

$names = array();
while($row =  mysql_fetch_assoc($resultClient)){
    $names[] = explode(",", $row['clients']);
}
print_r(array_unique(call_user_func_array('array_merge', $names)));
Sign up to request clarification or add additional context in comments.

3 Comments

Sir, this does not work! Please help me! while($row = mysql_fetch_assoc($resultClient)){ $names = explode(",", $row['clients']); echo '<pre>' . print_r(array_unique(call_user_func_array('array_merge', $names))).'</pre>'; } @u_mulder
I understand you and this worked! but ... all of them needed to be in my select tag. I tried this but did not work: <?php while($row = mysql_fetch_assoc($resultClient)){ $names[] = explode(",", $row['clients']); $cucul = print_r(array_unique(call_user_func_array('array_merge', $names))); echo '<option class="clients" value='.$names.'>'.$names.'</option>'; }
Do you understand what you do in your code? Why do you assign result of print_r to $cucul? Do you know what print_r returns?
1

You can just do a little trick:

Flatten, count and then remove all except the last.

$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($array)); 
$flatArray = [];
foreach($it as $v) {
   $flatArray[] = $v;           //Flatten array
}

//Note you can do array_unique on the flat array if you also need to flatten the array

$counts = array_count_values($flatArray); //Count 

foreach ($array as &$subarray) {
     foreach ($subarray as $index => $element) {
          $counts[$element]--;
          if ($counts[$element] > 0) { //If there's more than 1 left remove it
               unset($subarray[$index]);
          }
     }
} 

This will remove duplicates nested exactly on the 2nd level without flattening the original array.

http://sandbox.onlinephpfunctions.com/code/346fd868bc89f484dac48d12575d678f3cb53626

Comments

1

first you need to join your array before you can filter out the duplicates:

<?php
$allNames = [];
while($row =  mysql_fetch_assoc($resultClient)){
    $names = explode(",", $row['food']);
    $allNames[] = $names;
}

$allNames = array_merge(...$allNames);  //Join everything to a one dimensional array
$allNames = array_unique($allNames); // Only keep unique elementes

print_r($allNames);

2 Comments

I tried your snippet, I get only one food word? strange isnt it?
What about this snippet? A good answer will always have an explanation of what was done and why it was done in such a manner, not only for the OP but for future visitors to SO.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.