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);


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


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



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

PHP ints are typically 32 bits. Other packages provide higher-precision ints:

Thursday, December 15, 2022

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

>>> '' < ''

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 = ('', '')
>>> check_ipv4_in('', *ip_range)

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

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

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
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 :