Reputation: 503
I have this parametric array:
array[Tour Eiffel] = 0.6225
array[Arc de Triomphe] = 0.85
array[Avenue des Champs-Elysees] = 0.28
array[Place de la Concorde] = 0.3425
array[Palais Garnier] = 0.5025
array[Galeries Lafayette] = 0.35
array[Moulin Rouge] = 0.5425
array[Louvre] = 0.9425
array[Centre Pompidou] = 0.4425
array[Eglise Saint-Eustache] = 0.5825
I want to find in order the first five max elements and print the results how belows:
Louvre is 0.9425
Arc de Triomphe is 0.85
Tour Eiffel is 0.6225
Eglise Saint-Eustache is 0.5825
Moulin Rouge is 0.5425
I have used the function max() but this return only the max value and without the parametric key (example Louvre).
Upvotes: 0
Views: 64
Reputation: 54796
arsort($array); // sort array in reverse order
$top_vals = array_slice($array, 0, 5, true); // taking first 5 elements preserving keys
foreach ($top_vals as $k => $v)
echo $k . ' is ' . $v . '<br />';
Upvotes: 1
Reputation: 3873
Use arsort to sort an array in reverse order and maintain index association
arsort($arr, SORT_NUMERIC);
$count = 0;
foreach ($arr as $key => $val) {
echo "$key is $val";
$count += 1;
if ($count === 5) {
break;
}
echo '<br />';
}
Upvotes: 0