find the range of all values in a map in php

One way to find the range of all values in a map (associative array) in PHP is:

main.php
<?php
$myMap = array(
  "key1" => 10,
  "key2" => 20,
  "key3" => 15,
  "key4" => 5,
  "key5" => 25
);

$values = array_values($myMap);
$range = max($values) - min($values);

echo "The range of values in the map is: " . $range;
?>
231 chars
15 lines

In this solution, we first convert the map to an indexed array of values using array_values() function. Then we find the maximum and minimum values of the array using max() and min() functions respectively. Finally, we calculate the range by subtracting the minimum from maximum.

Note that this solution assumes that the map has numeric values. If the map has string values or other non-numeric values, then this solution may not work as expected.

related categories

gistlibby LogSnag