我现在在做什么:
$length = strlen($string);
if( $length > 5 && $length < $10 )
为了避免双倍长度测量:
if( strlen($string) > 5 && strlen($string) < 10 )
有没有更好的方法?像这样:
if( 5 < strlen($string) < 10 )
PHP 中没有 between 运算符。您可以执行以下操作:
if (in_array($someVar, range($min, $max)))
if (in_array(strlen($string), range(6, 9))) // In your case 5 and 10 are not included
你做的方式很好,很干净,可能比in_array+范围快一点。
不幸的是,
在 PHP 中没有保证的表达式求值顺序:请参阅此处的 PHP 语言开发人员讨论。因此,避免示例中的临时变量是有风险的,并且取决于 PHP 版本、平台等。
若要避免表达式中的重复计算,可以生成一个字符串类,并在计算长度以供以后访问后缓存长度。