0

I have an array which contains duplicate values. I want to sort the array so that the values with the most duplicates appear first in line.

I want an output like:

Rihanna
U2
Becca
Taylor Swift

My file that contains data:

rihanna
rihanna
rihanna
rihanna
taylor swift
becca
becca
u2
u2
u2

My code as is which wont work:

$input = file_get_contents('files');
$input = explode("\n", $input);

$acv = array_count_values($input);
$acv = arsort($acv); 
$result = array_keys($acv);
print_r($acv); //Outputs Blank
3
  • You can use php function array_unique for this. Commented Jun 9, 2017 at 11:04
  • I tried the following code before: print_r(array_unique($input)); but doesnt sort by order i want. Returns: Array ( [0] => rihanna [4] => taylor swift [5] => becca [7] => u2 [10] => ) Commented Jun 9, 2017 at 11:06
  • On what basis do you want the sorting to be done? You should do the sorting after the sanitizing the duplicates. Commented Jun 9, 2017 at 11:11

1 Answer 1

1

Here is your solution your array is :

$arr = array('rihanna','rihanna','rihanna','rihanna','taylor swift','becca','becca','u2','u2','u2');

$acv = array_count_values($input);
// If need to remove element with count = 1

foreach($acv as $key => $value)
{
    echo $value;
    if($value == 1)
    {
        unset($nArr[$key]);
    }
}
//End
$fArr = array_flip($acv);

krsort($fArr);
print_r(array_values($fArr));

//output
Array
(
    [0] => rihanna
    [1] => u2
    [2] => becca
    [3] => taylor swift
)
Sign up to request clarification or add additional context in comments.

1 Comment

That works a charm! Thank you very much. For educational purposes.. How would one go about making it display AS IS above, but without taylor swift? So display in order by highest dupe but dont display a result if there is only one record of it?

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.