Ivan Juarez Ivan Juarez - 3 years ago 126
PHP Question

PHP Find median value from array and return key and value?

I have an array of channels, so far I know how to return min and max values like this:

// clear from any empty channels
$channels = array_filter($scan['channels']);

// get min/max values
$min = array_keys($channels, min($channels));
$max = array_keys($channels, max($channels));
// this returns the channel name wich is what I need


So far I would like to get the median key (channel) name, how can I achieve this?

// this is the array of channels
Array
(
[chann_1] => 155.755
[chann_2] => 154.61
[chann_3] => 156.719
[chann_4] => 156.727
[chann_5] => 155.797
[chann_6] => 157.615
[chann_7] => 154.257
[chann_8] => 151.724
[chann_9] => 156.549
[chann_10] => 156.594
[chann_11] => 157.56
[chann_12] => 156.405
)

Answer Source

Try this:.

Sort the array.
Get the array keys.
Then half of count of array_keys is the median value. (I added round just in case).

$arr = Array(
"chann_1" => 155.755,
"chann_2" => 154.61,
"chann_3" => 156.719,
"chann_4" => 156.727,
"chann_5" => 155.797,
"chann_6" => 157.615,
"chann_7" => 154.257,
"chann_8" => 151.724,
"chann_9" => 156.549,
"chann_10" => 156.594,
"chann_11" => 157.56,
"chann_12" => 156.405);

Arsort($arr);
//Var_dump($arr);
$keys = array_keys($arr);
Echo $keys[round(count($keys)/2)];

https://3v4l.org/ER3d4

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download