user1032531 - 1 month ago 9x
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

`x`
value, and element 2 represents the element with the smallest
`x`
element.

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

``````\$array = [
['x'=>5,'y'=>3],
['x'=>9,'y'=>3],
['x'=>3,'y'=>3],
['x'=>7,'y'=>3]
];
``````

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()