Reputation: 1463
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 which 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
)
Upvotes: 1
Views: 5988
Reputation: 47992
array_slice()
is a direct tool to return the key-value pair after dividing the array count in half to find the position of the targeted element.
Code: (Demo)
asort($array);
var_export(
array_slice($array, intdiv(count($array), 2), 1, true)
);
Output:
array (
'chann_9' => 156.549,
)
As mentioned in my comment under the question, when there is an even number of elements in the array, the true median value will be the average of the middle two values. Because you can't have "half of a key", my script floors the calculation to the earlier of the two middle elements; if you want the later occurring element (of the middle two), you can use arsort()
or round the calculation up to the next integer (instead of rounding down as is done in my snippet).
Upvotes: 0
Reputation: 244
Usearray_search()
.$max_key=array_search($max,$yourArray);$min_key=array_search($min,$yourArray);$median=$max_key+$min_key/2;
of course it depends on your Array size.
Try $median=array_search($max+$min/2,$yourArra);
Upvotes: 0
Reputation: 23958
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)];
Upvotes: 2