-2

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.

Ivar
  • 4,655
  • 12
  • 45
  • 50
luna.romania
  • 199
  • 2
  • 12

2 Answers2

1

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.

Ivar
  • 4,655
  • 12
  • 45
  • 50
  • 1
    Good approach, I had something similar coming up but not much use posting the same thing twice. Didn't think about using min and max for the values. Also the answer would be complete for the OP with some clarification on what you did exactly. – Rimble Oct 20 '16 at 09:04
  • @Rimble Good call. – Ivar Oct 20 '16 at 09:07
  • @ivar Awesome approach. Can someone upvote my question please :) – luna.romania Oct 20 '16 at 09:11
  • @luna.romania It's not really a well formulated question, there is little code shown where you actually try and find your desired result. Overall not something that I would personally upvote. Have you read [How-to-ask](http://stackoverflow.com/help/how-to-ask)? Also adding in _UNIQUE IDEA_ in the title doesn't contribute to your question. – Rimble Oct 20 '16 at 10:03
0

this will do it code

foreach($myarray as $value)
{
if(in_array("10", $value, true))
{
    echo "Got 10";
}
}
Khetesh kumawat
  • 663
  • 7
  • 13