Input Array
$userArr = array("0"=>"Veronica", "1"=>"Alex", "2"=>"Joe", "3"=>"Alex", "4"=>"Veronica");
Here, user Veronica
and Alex
are repeated twice. How do I sort above array reverse alphabetical way even if count of two users are same i.e. Veronica => 2, Alex => 2
, only Veronica
will be displayed as output string.
$userArr = array("0"=>"Veronica", "1"=>"Alex", "2"=>"Joe", "3"=>"Alex", "4"=>"Veronica");
$userCnt = array_count_values($userArr);
foreach ($userCnt as $key => $val) {
echo "$key = $val
";
}
Output:
Veronica
Your Input Array:
$userArr = array("0"=>"Veronica", "1"=>"Alex", "2"=>"Joe", "3"=>"Alex", "4"=>"Veronica");
Count of an array:
echo count($userArr);
Reverse of an array:
arsort($userArr);
print_r($userArr);
Try this:
$userArr = array(
"0"=>"Veronica",
"1"=>"Alex",
"2"=>"Joe",
"3"=>"Alex",
"4"=>"Veronica");
//below line will first create an associative array with
//values as keys and their count as the value...
$arrayVals = array_count_values($userArr);
//next we sort this array in reverse alphabetically...
krsort($arrayVals);
//finally, print it :)
print_r($arrayVals);
//will print...
Array
(
[Veronica] => 2
[Joe] => 1
[Alex] => 2
)
UPDATE: Based on OP's explanation,I think he wants the value of the "last" alphabetical word in the array. If that is the case, the following code should do the trick:
$userArr = array("0"=>"Veronica", "1"=>"Alex", "2"=>"Joe", "3"=>"Alex", "4"=>"Veronica");
rsort($userArr);
echo current($userArr);
Using your approach, I'm assuming you want the one with the highest count that is also the last alphabetically:
$userArr = array("0"=>"Veronica", "1"=>"Alex", "2"=>"Joe", "3"=>"Alex", "4"=>"Veronica");
$userCnt = array_count_values($userArr);
ksort($userCnt);
$count = 0;
foreach ($userCnt as $key => $val) {
if($val >= $count) {
$result = $key;
$count = $val;
}
}
echo "$result appeared $count times";
$val
) is greater or equal to the last oneIt seems to be even simpler with your new comments. Sort the original and grab either the first or last depending on sort order:
rsort($userArr);
echo current($userArr);
//or
sort($userArr);
echo end($userArr);
If you need the array_count_values()
for whatever reason:
$userCnt = array_count_values($userArr);
krsort($userCnt);
echo key($userCnt);