Search code examples
phparraysarray-map

Effective and elegant way to get an item from array


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.


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