2

I have this array in the beginning

Array
(
    [0] => FRUIT
    [1] => MONKEY
    [2] => MONKEY
    [3] => MONKEY
    [4] => CANNABIS
)

with array_count_values() I get this

Array
(
    [FRUIT] => 1
    [MONKEY] => 3
    [CANNABIS] => 1
)

but actually I would like to sort it like here:

MONKEY 3 FRUIT 1
CANNABIS 1 (when the Integer is the same it doesn't have to get extra sorted alphabetic, that's not necessary)

I looked around, but couldn't find something appropriate.

Thank you in advance!

4
  • Why don't you just sort the array after using that function? Commented Dec 25, 2018 at 3:19
  • Hello, what do you mean exactly? Commented Dec 25, 2018 at 3:20
  • He means use rsort Commented Dec 25, 2018 at 3:27
  • Oh, thank you very much for this answer as well :) It actually isn't exactly the thing I was searching for, but I could have used it, so thanks again :) Commented Dec 25, 2018 at 3:49

1 Answer 1

2

asort is what you want :) http://php.net/manual/en/function.asort.php

asort — Sort an array and maintain index association

Basically sorts an associative array by value.

<?php
$words = [
   'FRUIT',
   'MONKEY',
   'MONKEY',
   'MONKEY',
   'CANNABIS',
];

// Count each occurrence
$counts = array_count_values($words);

// Sort the counts in descending order
arsort($counts);

// Display the results
var_dump($counts);

Produces:

Array
(
    [MONKEY] => 3
    [FRUIT] => 1
    [CANNABIS] => 1
)
Sign up to request clarification or add additional context in comments.

4 Comments

Ahhh thank you very much! For two things actually xd 1. Now I know for what var_dump() is for and I've also found arsort in another Thread here earlier but var_dump was the thing I was missing! Thank you to everyone who responded so quick! :)
But wait, could you please also tell me, how I can then get the key name and the value from var_dump or the above result?
Ahh okay, I just have to continue to use the array normally, thank you again :)
Yes :) var_dump only prints out the results for debugging. The array is just a normal array.

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.