Jump to content

Quick Question About Array


johnsmith153

Recommended Posts

I have the following info in an array:

 

Jim, Bob, Dave, Jim, Jim, Jim, Paul, Jim

 

As you can see above - Jim has 5 entries

 

I need to sort it so I can check for the name and number of occurences of the 1st, 2nd,3rd most popular.

 

I know array_count_values can do sort of this - but as far as I am aware you need to know the value you are searching (i.e Jim)  Assume I dont know the expected value - all I know is that I want to return the one with the most occurences.

Link to comment
https://forums.phpfreaks.com/topic/121925-quick-question-about-array/
Share on other sites

<?php
$array = array('jim', 'bob', 'dave', 'jim', 'jim', 'jim', 'paul', 'jim');
$nums = array_count_values($array);
sort($nums, SORT_NUMERIC);
$sorted = array_slice($nums, 0, 3);
foreach ($sorted as $name=>$count) {
  echo "$name appeared $count times";
}

OUTSTANDING - quick response.

 

however, it doesn't work.

 

I can see it can work, must be something slightly out:

 

I get this returned:

0 appeared 1 times1 appeared 1 times2 appeared 1 times

 

I will try to modify, see if I can beat DarkWater to the solution!

Duh, forgot about keys being reset by sort() and the way it sorts.  Use arsort() instead, with the same flags.

 

<?php
$array = array('jim', 'bob', 'dave', 'jim', 'jim', 'jim', 'paul', 'jim');
$nums = array_count_values($array);
arsort($nums, SORT_NUMERIC);
$sorted = array_slice($nums, 0, 3);
foreach ($sorted as $name=>$count) {
  echo "$name appeared $count times<br />\n";
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.