luna.romania - 4 months ago 18

PHP Question

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`

For Example, I want to search, if

`$x`

`10`

`20`

`299`

`315`

`156`

`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.