Viewed   107 times

Is there a way to test a range without doing this redundant code:

if ($int>$min && $int<$max)

?

Like a function:

function testRange($int,$min,$max){
    return ($min<$int && $int<$max);
}

usage:

if (testRange($int,$min,$max)) 

?

Does PHP have such built-in function? Or any other way to do it?

 Answers

5

I don't think you'll get a better way than your function.

It is clean, easy to follow and understand, and returns the result of the condition (no return (...) ? true : false mess).

Saturday, September 3, 2022
5

PHP ints are typically 32 bits. Other packages provide higher-precision ints: http://php.net/manual/en/language.types.integer.php

Thursday, December 15, 2022
 
1

You can't really do string comparisons on a dot separated list of numbers because your test will simply fail on input say 1.1.99.99 as '9' is simply greater than '2'

>>> '1.1.99.99' < '1.1.255.255'
False

So instead you can convert the input into tuples of integers through comprehension expression

def convert_ipv4(ip):
    return tuple(int(n) for n in ip.split('.'))

Note the lack of type checking, but if your input is a proper IP address it will be fine. Since you have a 2-tuple of IP addresses, you can create a function that takes both start and end as argument, pass that tuple in through argument list, and return that with just one statement (as Python allows chaining of comparisons). Perhaps like:

def check_ipv4_in(addr, start, end):
    return convert_ipv4(start) < convert_ipv4(addr) < convert_ipv4(end)

Test it out.

>>> ip_range = ('1.1.0.0', '1.1.255.255')
>>> check_ipv4_in('1.1.99.99', *ip_range)
True

With this method you can lazily expand it to IPv6, though the conversion to and from hex (instead of int) will be needed instead.

Friday, December 9, 2022
 
2

If you are just checking whether any part of the offer overlaps any part of the range, it's simple.

if ($offerStartTime < $endTime && $offerEndTime > $startTime)  {
    echo 'The ranges overlap';
}

Here's a picture representing all the possibilities of overlap and non-overlap to visualize why this works.

Based on your inputs and expected false outputs, I used < and >. If you wanted to also include ranges that intersected at a point, you would need to use <= and >= instead.

Sunday, November 27, 2022
 
4

I am aware that this question already has an answer.... But just in case, this also works.

int x = (int) Math.sqrt(input);
if(Math.pow(x,2) == input)
    //Do stuff
Tuesday, September 27, 2022
 
yaman
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :