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

UNIQUE IDEA : How do I search - a range - inside a multi-dimensional array in php?

its 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, n then between 299 to 315, n then between 156 to 199. I hope m clear now.

Thanks

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.