user1911283
user1911283

Reputation: 111

find highest value in associative array

I've got an array which looks like this:

array(10) {
  [0]=>
  array(4) {
    [0]=>
    array(5) {
    ...
    }
    [1]=>
    array(5) {
    ...
    }
    [2]=>
    array(5) {
    ...
    }
    ["opt"]=>
    float(0.5)
  }
  [1]=>
  array(4) {
    [0]=>
    array(5) {
    ...
    }
    [1]=>
    array(5) {
    ...
    }
    [2]=>
    array(5) {
    ...
    }
    ["opt"]=>
    float(1)
  }
  .....
}

I want to find out the Key of the Array of the first layer, which has the highest value at the key 'opt'. I hope you got what i mean. Sorry for that sentence, but it was kind of hard to explain! ;)

EDIT: What I've thought of was the use of max() creating all the entries with the use of foreach. I wasnt sure if this would be the best way.

Upvotes: 0

Views: 4231

Answers (2)

Paul T. Rawkeen
Paul T. Rawkeen

Reputation: 4114

What about max() + array_map()?

$max = max(
    array_map(function (array $layer) {
        return (float)$layer['opt'];
    }, $layers)
)

Upvotes: 0

nap.gab
nap.gab

Reputation: 451

You can use the max() function

if your array have a constant length "n"

$maxValue=max($array[0]["opt"],$array[1]["opt"], ... $array[n]["opt"]);

else

$i=0;
foreach($array as $value)  {
   $opts[$i]=$value["opt"];
   $i++;
}
$maxValue=max($opts);

Upvotes: 3

Related Questions