-4

I have a variable of int type called myNumber and I need to know if it is in the interval [100, 200].

Example:

if (myNumber in (100, 200)) {
    echo 'Yes';
}

I wonder if PHP has a in function or similar.

Roby Sottini
  • 2,117
  • 6
  • 48
  • 88
  • 2
    You could simply write one yourself. `return $input >= $left && $input <= $right` – Sindhara Mar 11 '19 at 11:50
  • 3
    if (myNumber > 100 && myNumber < 200) is the fastest way. – PierreD Mar 11 '19 at 11:51
  • 3
    google's first result when searching for `php between` : https://stackoverflow.com/questions/5029409/how-to-check-if-an-integer-is-within-a-range – Sindhara Mar 11 '19 at 11:52
  • No one answered `$range = [100,200]; if($number >= $range[0] && $number <= $range[1])` or `$min` `$max` must be slacking.... Range does have the benefit of using a `step` other then one. etc... – ArtisticPhoenix Mar 11 '19 at 12:16

2 Answers2

2

Php does not have it, but you can create it like this example.


function in($number,$min,$max){
    if($number >= $min and $number <= $max){
       return true;
    }
    return false;
}
Vidal
  • 2,605
  • 2
  • 16
  • 32
0

You can use range and in_array function

<?php
$x = 150;
if ( in_array($x, range(100,200)) ) {
    echo 'Number '.$x.' is in range';
}
else
{
    echo 'Number '.$x.' is not in range';
}

?>

Also, You can create your own function in php for the same

<?php
$x = 150;

function in_range($x)
{
    if ( in_array($x, range(100,200)) ) 
    {
       return true;
    }
    else
    {
        return false;
    }
}

$result = in_range($x);

?>

To know more details you can read here

Ankur Tiwari
  • 2,762
  • 2
  • 23
  • 40
  • 1
    the range() will kill performance. What if the numbers are 1, 100000, that means you create a massive array that will be looped to find a matching number. Not good... – Andreas Mar 11 '19 at 12:47