find the median of all keys in a map in php

To find the median of all keys in a map in PHP, first, we need to extract all the keys of the map and store them in an array. Once we have the array of keys, we can use the median function to calculate the median.

Here's the code:

main.php
$map = ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5]; //sample map

$keys = array_keys($map); //extract keys and store them in an array

sort($keys); //sort the array of keys

$count = count($keys); //get the count of keys

if ($count % 2 == 0) { //if the count is even
    $median = ($keys[($count/2)-1] + $keys[$count/2]) / 2; //calculate the median
} else { //if the count is odd
    $median = $keys[(int) ($count/2)]; //calculate the median
}

echo $median; //print the median
486 chars
16 lines

This code will output c, which is the median of the keys a, b, c, d, e.

related categories

gistlibby LogSnag