Find out if a value is within a range with one if clause in PHP?

60 Views Asked by At

What I'm doing now:

$length = strlen($string);
if( $length > 5 && $length < $10 )

In order to avoid double length measurement:

if( strlen($string) > 5 && strlen($string) < 10 ) 

Is there a nicer way of doing this? Something like:

if( 5 < strlen($string) < 10 )
2

There are 2 best solutions below

0
On

There is no between operator in PHP. You could do something like:

if (in_array($someVar, range($min, $max)))

if (in_array(strlen($string), range(6, 9))) // In your case 5 and 10 are not included

The way you are doing is nice and clean, and probably a bit faster than the in_array+range.

0
On

Unfortunately in PHP there is no guaranteed expression evaluation order: see PHP language developer discussion here. So, avoiding the temporary variable in your exapmle will by risky and depends on the PHP version, platform, etc.

To avoid double evaluation in an expression, you can build a string class and cache the length once it has been evaluated for later access.