# How to find the closest value in a multidimensional array?

Hello.
Not sure how to correctly formulate a question, write as is:
This multidimensional array of the following form:
``````[
[1, 1, 1],
[1, 2, 1],
[1, 2, 2],
[1, 5, 4],
[1, 5, 6],
[2, 1, 6],
[2, 2, 2],
]``````

The array consists of arrays of 3 and sorted in ascending order. And this for example, the following array:
`[1, 5, 5]`
How to find the value in the first array, which would be the closest (less than or equal) to the second array. For example, for this case it will be set to [1, 5, 4].
I hope the essence of the issue is clear.
June 3rd 19 at 20:22
June 3rd 19 at 20:24
Solution
Once sorted, then you just go straight until you find an element larger than the specified value. To return the previous one.

``````function nearest( \$sample, \$arr) {
\$found = false;
foreach( \$arr AS \$row) {
if(\$row[0] <= \$sample[0] && \$row[1] <= \$sample[1] && \$row[2] <= \$sample[2]) \$found = \$row;
else break;
}

return \$found;
}

\$data = [
[1, 1, 1],
[1, 2, 1],
[1, 2, 2],
[1, 5, 4],
[1, 5, 6],
[2, 1, 6],
[2, 2, 2],
];

echo implode(',', nearest( [1,5,5], \$data)); // 1,5,4``````
Thank you! - Bulah72 commented on June 3rd 19 at 20:27
June 3rd 19 at 20:26
``````/**
* @param array \$input
* @param array \$items
*
* @return int|null
*/
function compare(array \$input, array \$items)
{
foreach (\$items as \$index => \$item) {
\$compareResult = version_compare(implode('.', \$input), implode('.', \$item));
if (\$compareResult <= 0) {
if (\$compareResult === 0 || !array_key_exists(\$index - 1, \$items)) {
return \$index;
}

return \$index - 1;
}
}

return null;
}

\$items = [
[1, 1, 1],
[1, 2, 1],
[1, 2, 2],
[1, 5, 4],
[1, 5, 6],
[2, 1, 6],
[2, 2, 2],
];
\$input = [1, 5, 5];

if (null === \$index = compare(\$input, \$items)) {