Search code examples
phparraysduplicates

Find duplicate values in array and save them in a separate array


Bit of a strange one, so I am looking to get all duplicates in an array, and save each of them in a separate array. It's a bit difficult to explain so I will try with an example.

$array = array('apple', 'apple', 'apple', 'orange', 'orange', 'banana');

I am looking to find all duplicates (in this instance, apples and oranges) and save each in their own separate array, which will then be counted afterwards to find out how many of each duplicate exists in each of the arrays.

Once I have counted them, I will then run a mysqli query dependant on the amount found (there can only be a maximum of 6 of the same item).

An example ideal output would be

$array1 to be ('apple', 'apple', 'apple'), $array2 to be ('orange', 'orange') and $array3 would be ('banana')

I apologise in advance if this question doesn't make much sense, but it's pretty difficult for me to explain.


Solution

  • $count = [];
    $array = ['apple', 'apple', 'apple', 'banana', 'banana', 'orange', 'orange'];
    
    foreach ($array as $a) {
        $count[$a]++;
    }
    
    print_r($count);
    

    Output (Demo):

    Warning: Undefined array key "apple" in /in/XfnEb on line 7
    
    Warning: Undefined array key "banana" in /in/XfnEb on line 7
    
    Warning: Undefined array key "orange" in /in/XfnEb on line 7
    Array
    (
        [apple] => 3
        [banana] => 2
        [orange] => 2
    )
    

    You could then loop through the one array with key => value obtaining the 'fruit' and occurrence.

    Edit: You'll need to uppercase/lowercase the key if you're case-insensitive searching.