luna.romania luna.romania - 1 month ago 5
PHP Question

How do I search if a value is in a range, inside a multi-dimensional array in PHP?

It's a simple question, but puzzling me:

$myarray = array(
array(10,20),
array(299, 315),
array(156, 199)
);


How do I check if given
$x
, lies in between, in any of those particular individual array values? I want to search each individual entry array.

For Example, I want to search, if
$x
is somewhere between:
10
to
20
and then between
299
to
315
and then between
156
to
199
.

Answer

Try this:

function is_in_array_range($array, $search) {
    foreach ($array as $value) {
        $min = min($value);
        $max = max($value);

        if ($search >= $min && $search <= $max) {
            return true;
        }
    }

    return false;
}

$myarray = array(
    array(10,20),
    array(299, 315),
    array(156, 199)
);

is_in_array_range($myarray, 9);  // Returns false
is_in_array_range($myarray, 11); // Returns true

The function is_in_array_range() will take two arguments. The array, and the value you want to check is in the range.

When it enters, it will loop over all elements in the array. Every time it gets the highest and lowest value of the nested array (min() and max() function), and checks if the value you are looking for is between them. If this is the case, return true (this also stops the function). If true is never reached, the value is not found, so at the end of the function, return false.