user1032531 user1032531 - 1 year ago 51
PHP Question

Find array element with greatest or smallest sub-array element value

Element 1 of the following array represents the element with the greatest

value, and element 2 represents the element with the smallest

Without looping over each array using PHP code, how can the index of the element with the greatest and smallest
be determined?

$array = [

Answer Source

Extract the x column and compute it:

$x = array_column($array, 'x');
$min = min($x);
$max = max($x);

Or, as JustOnUnderMillions points out:

list($min, $max) = [min($x=array_column($array, 'x')), max($x)];

To get the index of the array containing that value, just use array_search(). It will return the first key if there are multiple identical values:

$x = array_column($array, 'x');
$min = array_search(min($x), $x, true);
$max = array_search(max($x), $x, true);

PHP >= 5.5.0 needed for array_column() or use the PHP Implementation of array_column()