0

I have a simple array like this:

Array(
    [a] =>  1,
    [b] =>  5,
    [c] => 10
)

Now I want to get the key/value pair for the highest and lowest array value. Means the expected output would be:

//Max value
Key:    c
Value: 10
//Min value
Key:    a
Value:  1

I tried something like this:

$max_key = max( array_keys( $array ) ); 
Rizier123
  • 58,877
  • 16
  • 101
  • 156
The Old County
  • 89
  • 13
  • 59
  • 129
  • `array_keys($a, max($a))` – splash58 Sep 16 '16 at 15:19
  • To get the key of the smallest value should be straightforward if you look at the duplicate. (Note that if you use `array_keys()` in your solution you will get an array with **all** keys back from the elements with the highest value, while if you use `array_search()` you will only get the **first key** of the first element with the highest value back). – Rizier123 Sep 16 '16 at 15:22
  • _ that just then returns -- just the key and not the value -- need both – The Old County Sep 16 '16 at 15:25
  • {"label": "super club", "value": 25} – The Old County Sep 16 '16 at 15:28
  • @TheOldCounty Well from your `max()` and `min()` call you get the highest and lowest value and with `array_keys()`/`array_search()` you can get the corresponding keys. Then you got both keys and values. – Rizier123 Sep 16 '16 at 15:28
  • It sounds like a borky way of obtaining the results -- by running two different methods -- a max and a min - twice -- to then glue the results together? – The Old County Sep 16 '16 at 15:29
  • @TheOldCounty PHP does not provide you with `build_me_a_pink_green_house()` function, but it does provide you with tools like `hammer()` or `screwdriver()`. So with the first calls you can get the values and as you need to with the second call obtain the keys from the values. – Rizier123 Sep 16 '16 at 15:33
  • Oh come on man - I was just asking you if there was a cleaner solution – The Old County Sep 16 '16 at 15:34
  • @TheOldCounty As I was trying to explain to you with the analogy above, PHP does not provide you with a function for everything, but it does provide you with functions to get what you want. So the only thing you can improve is to salve the max/min values first, something like this: https://3v4l.org/C1VFA Also please don't post solutions inside your question. – Rizier123 Sep 16 '16 at 15:41
  • I mean of course you can put that inside a function yourself and then you have created your own function. – Rizier123 Sep 16 '16 at 15:48

1 Answers1

1

Well you almost named then, max() and min() return the max value and min value of array

echo max(array(2, 4, 5)); // 5
echo min(array(2, 4, 5)); // 2
Nidhin Chandran
  • 846
  • 8
  • 19
rak007
  • 973
  • 12
  • 26