Question

For example, i've got an array like this:

$a = array(
    0 => array(
        'foo' => 42
    ),
    1 => array(
        'foo' => 143
    ),
    2 => array(
        'foo' => 4
    )
);

And i need to get an element with a maximum value in 'foo'. Current code is this:

$foos = array_map(function($v) {
    return $v['foo'];
}, $a);
$keys = array_keys($foos, max($foos));
$winner = $a[$keys[0]];
print_r($winner);

Which is a scary thing.

Was it helpful?

Solution

You can try with:

$input  = array(
  array('foo' => 42),
  array('foo' => 143),
  array('foo' => 4),
);

$output = array_reduce($input, function($a, $b) {
  return $a['foo'] > $b['foo'] ? $a : $b;
});

Output:

array (size=1)
  'foo' => int 143

OTHER TIPS

Most elegant?

$maxValue = max($a);

http://www.php.net/manual/en/function.max.php

Works even with multi-dimensional:

<?php
$a = array(
    0 => array(
        'foo' => 42
    ),
    1 => array(
        'foo' => 143
    ),
    2 => array(
        'foo' => 4
    )
);

$maxValue = max($a);
print_r($maxValue["foo"]);
echo $maxValue["foo"];

Output with echo 143.

Output with print_r() Array ( [foo] => 143 )

Just run the foreach yourself. Readable and easy.

$highest_foo = PHP_INT_MIN;
$result = null;
foreach ($a as $key=>$foo) {
    if ($foo['foo'] > $highest_foo) {
       $result = $a[$key];
       $highest_foo = $foo['foo'];
    }
}
print_r($result);
$array = array(
    0 => array(
        'foo' => 42
    ),
    1 => array(
        'foo' => 143
    ),
    2 => array(
        'foo' => 4
    )
);

$maxs = array_keys($array, max($array));

print_r(max($array));//Highest value
print_r($maxs);//Key of hishest value
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top