$str == '' 之间有区别吗? PHP 中的 strlen($str) == 0 ?

发布于 2024-07-09 21:21:47 字数 86 浏览 17 评论 0原文

正如标题所说: PHP 中 $str == '' 和 strlen($str) == 0 之间有区别吗? 是否存在真正的速度差异?其中一个比另一个更好用吗?

As the title says: Is there a difference between $str == '' and strlen($str) == 0 in PHP? Is there any real speed difference and is one better to use than the other?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

卸妝后依然美 2024-07-16 21:21:47

我发现这样做更清楚
“if (!$str)” ..不确定 '==' 但'!' 应该能够产生更好的优化技术,因为没有进行任何类型转换,并且对于字符串、数组、布尔值、数字来说是安全的......

i find it clearer to just do
"if (!$str)" .. not sure about '==' but '!' should be able to yeld better optimization techniques, as no typecasting is ever done, and is safe for strings, arrays, bools, numbers...

薄情伤 2024-07-16 21:21:47

是的,有一个重要的区别。 == 运算符执行类型转换,因此它并不总是会执行您期望的操作。 例如,(0 == "") 返回 true。 所以你假设 $str 实际上是一个字符串。 如果您确定是这种情况,或者您不关心转换,那么也没关系。 否则,您应该使用 ===,并采取措施确保您正在比较字符串。

Yes, there is an important difference. The == operator does type conversion, so it's not always going to do what you expect. For example, (0 == "") returns true. So you're making an assumption that $str is actually a string. If you're sure this is the case, or if you don't care about the conversions, then it's fine. Otherwise you should use ===, and take steps to ensure that you're comparing strings.

谈情不如逗狗 2024-07-16 21:21:47

主要区别在于 $str == '' 对于任何相当于空字符串的内容都会返回 true(0 和 false,等等)。

您应该使用 === 运算符来测试实际的空字符串,或者,如果您不介意转换和测试行为,则只需使用 !$str (考虑 empty() 以及,取决于实际意图),我发现它的意图比 $x == '' 更清晰(他是否错过了 = 符号,实际上想要测试空字符串吗?。)

仅当您确实需要字符串的长度时才使用 strlen($str) 。

最重要的是,使用正确的工具来完成工作,并根据代码的意图判断哪个工具是正确的。

vinko@parrot:~$ cat emptytest.php
<?php
$a = "";
$b = 0;
$c = false;
$d = "Hi!";

function is_empty1($x) { return $x == ''; }
function is_empty2($x) { return strlen($x) == 0; }
function is_empty3($x) { return $x === ''; }

function check_empty($arr) {
        foreach ($arr as $v) {
                echo "value is ";
                var_dump($v);
                echo "   \$x == ''      ";
                var_dump(is_empty1($v));
                echo "   strlen($x) == 0 ";
                var_dump(is_empty2($v));
                echo "   \$x === ''     ";
                var_dump(is_empty3($v));
        }
}

check_empty(array($a,$b,$c,$d));

?>
vinko@parrot:~$ php emptytest.php
value is string(0) ""
   $x == ''      bool(true)
   strlen() == 0 bool(true)
   $x === ''     bool(true)
value is int(0)
   $x == ''      bool(true)
   strlen() == 0 bool(false)
   $x === ''     bool(false)
value is bool(false)
   $x == ''      bool(true)
   strlen() == 0 bool(true)
   $x === ''     bool(false)
value is string(3) "Hi!"
   $x == ''      bool(false)
   strlen() == 0 bool(false)
   $x === ''     bool(false)

The main difference is that $str == '' will return true for anything that's equivalent to the empty string (0 and false, among others).

You should use either the === operator to test for an actual empty string or, if you don't mind the convert and test behavior, just use !$str (consider empty() as well, depending on the actual intent), which I find clearer in intent than $x == '' (Did he miss an = sign and actually wants to test for an empty string?.)

Use strlen($str) only when you really are after the length of a string.

Bottom line, use the proper tool for the job, judging which tool is proper based on the intent of the code.

vinko@parrot:~$ cat emptytest.php
<?php
$a = "";
$b = 0;
$c = false;
$d = "Hi!";

function is_empty1($x) { return $x == ''; }
function is_empty2($x) { return strlen($x) == 0; }
function is_empty3($x) { return $x === ''; }

function check_empty($arr) {
        foreach ($arr as $v) {
                echo "value is ";
                var_dump($v);
                echo "   \$x == ''      ";
                var_dump(is_empty1($v));
                echo "   strlen($x) == 0 ";
                var_dump(is_empty2($v));
                echo "   \$x === ''     ";
                var_dump(is_empty3($v));
        }
}

check_empty(array($a,$b,$c,$d));

?>
vinko@parrot:~$ php emptytest.php
value is string(0) ""
   $x == ''      bool(true)
   strlen() == 0 bool(true)
   $x === ''     bool(true)
value is int(0)
   $x == ''      bool(true)
   strlen() == 0 bool(false)
   $x === ''     bool(false)
value is bool(false)
   $x == ''      bool(true)
   strlen() == 0 bool(true)
   $x === ''     bool(false)
value is string(3) "Hi!"
   $x == ''      bool(false)
   strlen() == 0 bool(false)
   $x === ''     bool(false)
深爱不及久伴 2024-07-16 21:21:47

我执行了一个简单的基准测试。 (我从来没有做过,所以这可能完全无效。)它测试 == ''、strlen() == 0、=== '' 和 strlen() === 0。

header('Content-type: text/plain');

// -- Testing == '';

$string = '';

$startTime = microtime(true);
for($i = 0; $i < 10000000; ++$i)
    $string == '';
$endTime = microtime(true);
echo "\$string = ''; \$string == ''; took " . ($endTime - $startTime) . " seconds\n";

$string = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa';

$startTime = microtime(true);
for($i = 0; $i < 10000000; ++$i)
    $string == '';
$endTime = microtime(true);
echo "\$string = '$string'; \$string == ''; took " . ($endTime - $startTime) . " seconds\n";

$startTime = microtime(true);
for($i = 0; $i < 10000000; ++$i)
    '' == '';
$endTime = microtime(true);
echo "'' == ''; took " . ($endTime - $startTime) . " seconds\n";

// -- Testing strlen() == 0;

$string = '';

$startTime = microtime(true);
for($i = 0; $i < 10000000; ++$i)
    strlen($string) == 0;
$endTime = microtime(true);
echo "\$string = ''; strlen(\$string) == 0; took " . ($endTime - $startTime) . " seconds\n";

$string = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa';

$startTime = microtime(true);
for($i = 0; $i < 10000000; ++$i)
    strlen($string) == 0;
$endTime = microtime(true);
echo "\$string = '$string'; strlen(\$string) == 0; took " . ($endTime - $startTime) . " seconds\n";

$startTime = microtime(true);
for($i = 0; $i < 10000000; ++$i)
    strlen('') == 0;
$endTime = microtime(true);
echo "strlen('') == ''; took " . ($endTime - $startTime) . " seconds\n";

// -- Testing === '';

$string = '';

$startTime = microtime(true);
for($i = 0; $i < 10000000; ++$i)
    $string === '';
$endTime = microtime(true);
echo "\$string = ''; \$string === ''; took " . ($endTime - $startTime) . " seconds\n";

$string = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa';

$startTime = microtime(true);
for($i = 0; $i < 10000000; ++$i)
    $string === '';
$endTime = microtime(true);
echo "\$string = '$string'; \$string === ''; took " . ($endTime - $startTime) . " seconds\n";

$startTime = microtime(true);
for($i = 0; $i < 10000000; ++$i)
    '' === '';
$endTime = microtime(true);
echo "'' === ''; took " . ($endTime - $startTime) . " seconds\n";

// -- Testing strlen() === 0;

$string = '';

$startTime = microtime(true);
for($i = 0; $i < 10000000; ++$i)
    strlen($string) === 0;
$endTime = microtime(true);
echo "\$string = ''; strlen(\$string) === 0; took " . ($endTime - $startTime) . " seconds\n";

$string = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa';

$startTime = microtime(true);
for($i = 0; $i < 10000000; ++$i)
    strlen($string) === 0;
$endTime = microtime(true);
echo "\$string = '$string'; strlen(\$string) === 0; took " . ($endTime - $startTime) . " seconds\n";

$startTime = microtime(true);
for($i = 0; $i < 10000000; ++$i)
    strlen('') === 0;
$endTime = microtime(true);
echo "strlen('') === ''; took " . ($endTime - $startTime) . " seconds\n";

结果:

$string = ''; $string == ''; took 1.01983308792 seconds
$string = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'; $string == ''; took 1.04193401337 seconds
'' == ''; took 1.06608295441 seconds
$string = ''; strlen($string) == 0; took 2.1510848999 seconds
$string = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'; strlen($string) == 0; took 2.27101397514 seconds
strlen('') == ''; took 2.5775551796 seconds
$string = ''; $string === ''; took 0.854554176331 seconds
$string = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'; $string === ''; took 0.714010000229 seconds
'' === ''; took 0.749495983124 seconds
$string = ''; strlen($string) === 0; took 1.9263010025 seconds
$string = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'; strlen($string) === 0; took 1.95309996605 seconds
strlen('') === ''; took 2.40874910355 seconds

如您所见,比较 '' 的速度大约是比较字符串长度的两倍。 另外,使用 === 比使用 == 稍快,而且它是类型安全的! 好的。

I performed a simple benchmark. (I've never done one so this may be completely invalid.) It tests == '', strlen() == 0, === '', and strlen() === 0.

header('Content-type: text/plain');

// -- Testing == '';

$string = '';

$startTime = microtime(true);
for($i = 0; $i < 10000000; ++$i)
    $string == '';
$endTime = microtime(true);
echo "\$string = ''; \$string == ''; took " . ($endTime - $startTime) . " seconds\n";

$string = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa';

$startTime = microtime(true);
for($i = 0; $i < 10000000; ++$i)
    $string == '';
$endTime = microtime(true);
echo "\$string = '$string'; \$string == ''; took " . ($endTime - $startTime) . " seconds\n";

$startTime = microtime(true);
for($i = 0; $i < 10000000; ++$i)
    '' == '';
$endTime = microtime(true);
echo "'' == ''; took " . ($endTime - $startTime) . " seconds\n";

// -- Testing strlen() == 0;

$string = '';

$startTime = microtime(true);
for($i = 0; $i < 10000000; ++$i)
    strlen($string) == 0;
$endTime = microtime(true);
echo "\$string = ''; strlen(\$string) == 0; took " . ($endTime - $startTime) . " seconds\n";

$string = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa';

$startTime = microtime(true);
for($i = 0; $i < 10000000; ++$i)
    strlen($string) == 0;
$endTime = microtime(true);
echo "\$string = '$string'; strlen(\$string) == 0; took " . ($endTime - $startTime) . " seconds\n";

$startTime = microtime(true);
for($i = 0; $i < 10000000; ++$i)
    strlen('') == 0;
$endTime = microtime(true);
echo "strlen('') == ''; took " . ($endTime - $startTime) . " seconds\n";

// -- Testing === '';

$string = '';

$startTime = microtime(true);
for($i = 0; $i < 10000000; ++$i)
    $string === '';
$endTime = microtime(true);
echo "\$string = ''; \$string === ''; took " . ($endTime - $startTime) . " seconds\n";

$string = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa';

$startTime = microtime(true);
for($i = 0; $i < 10000000; ++$i)
    $string === '';
$endTime = microtime(true);
echo "\$string = '$string'; \$string === ''; took " . ($endTime - $startTime) . " seconds\n";

$startTime = microtime(true);
for($i = 0; $i < 10000000; ++$i)
    '' === '';
$endTime = microtime(true);
echo "'' === ''; took " . ($endTime - $startTime) . " seconds\n";

// -- Testing strlen() === 0;

$string = '';

$startTime = microtime(true);
for($i = 0; $i < 10000000; ++$i)
    strlen($string) === 0;
$endTime = microtime(true);
echo "\$string = ''; strlen(\$string) === 0; took " . ($endTime - $startTime) . " seconds\n";

$string = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa';

$startTime = microtime(true);
for($i = 0; $i < 10000000; ++$i)
    strlen($string) === 0;
$endTime = microtime(true);
echo "\$string = '$string'; strlen(\$string) === 0; took " . ($endTime - $startTime) . " seconds\n";

$startTime = microtime(true);
for($i = 0; $i < 10000000; ++$i)
    strlen('') === 0;
$endTime = microtime(true);
echo "strlen('') === ''; took " . ($endTime - $startTime) . " seconds\n";

Results:

$string = ''; $string == ''; took 1.01983308792 seconds
$string = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'; $string == ''; took 1.04193401337 seconds
'' == ''; took 1.06608295441 seconds
$string = ''; strlen($string) == 0; took 2.1510848999 seconds
$string = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'; strlen($string) == 0; took 2.27101397514 seconds
strlen('') == ''; took 2.5775551796 seconds
$string = ''; $string === ''; took 0.854554176331 seconds
$string = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'; $string === ''; took 0.714010000229 seconds
'' === ''; took 0.749495983124 seconds
$string = ''; strlen($string) === 0; took 1.9263010025 seconds
$string = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'; strlen($string) === 0; took 1.95309996605 seconds
strlen('') === ''; took 2.40874910355 seconds

As you can see, comparing to '' is about twice as fast as comparing the length of the string. Also, using === is slightly faster than using ==, and it's type safe! Nice.

九厘米的零° 2024-07-16 21:21:47

即使存在速度差异,您也不应该选择更快的那个。 选那个比较清晰的。

Even if there was a speed difference, you should not pick the faster one. Pick the clearer one.

二智少女猫性小仙女 2024-07-16 21:21:47

$str == '' 是更好的做法。 PHP 中可能没有太大区别,因为它知道字符串的长度,但如果您随后使用较低级语言进行一些工作,那么这将是一个非常坏的习惯。

$str == '' is better practice. There probably isn't much difference in PHP, since it knows the length of its strings, but it'd be a really bad habit to have if you then went and did some work in a lower-level language.

十雾 2024-07-16 21:21:47

也许: !strlen($str)

Maybe: !strlen($str)

余生共白头 2024-07-16 21:21:47

strlen($str) == 0 需要调用 strlen 并进行比较。 $str == '' 只是一个比较。

strlen($str) == 0 requires a call to strlen and a call to do the comparison. $str == '' is just a comparison.

愿得七秒忆 2024-07-16 21:21:47

执行 $str=='' 时可能会出现一些类型转换问题。 例如,考虑 $strfalse(布尔值)或 0(整数)的情况。 他们可能也只是平等。 我对此不太确定,所以你应该稍微考虑一下。 安全的方法是执行 $str===''

There might be some type-conversion issues when doing $str==''. For example, consider cases when $str is false (boolean) or 0 (integer). They might just come out equal too. I'm not exactly sure about this, so you should muck around with it a bit. The safe way would be to do $str===''.

蓝咒 2024-07-16 21:21:47

我敢肯定,速度差异太小了,无关紧要。 最好的使用方法是更具可读性的方法。 这里有另外两个替代方案:

if (empty($str)) {
    ...
}

if (!$str) {
    ...
}

注意: 如果 $str == '0',它们的计算结果都将为 true。

The speed difference is too small to matter, I'm sure. The best method to use is the more readable one. Here are two other alternatives:

if (empty($str)) {
    ...
}

if (!$str) {
    ...
}

Note: These will both evaluate to true if $str == '0'.

抚你发端 2024-07-16 21:21:47

不,它们并不相同(如上所述),但出于您的目的,它们可能可以互换。

快点? 定性地讲,很难想象两种方式的差异会产生重大影响的情况,但可以看到其他更定量的答案。 这里基于速度的编码可能是我们最喜欢的贬义词的一个例子,它可以缩写为“pi”。

哪个最好?

这取决于您想要确认的关于 $str 的断言,以及您想要调用的结果。

您会看到的另一个常见模式是

!$str

,它通常给出相同的结果 - 如果您只是想测试不可用的字符串值,无论它为什么不可用,这可能是合适的 - 这可能是缺少初始化、初始化默认、赋值等。(顺便说一句,我并不是支持或反对这种表示。)请记住,您的决定可能会产生后果,并且您需要根据您的方式了解 $str 状态会调用哪些后果已经写好了代码。 (请注意,您可能没有在我们的任何一个选项中明确涵盖 $str 值/状态。)

No, they're not the same (as explained above), but for your purposes they might be interchangeable.

Faster? Qualitatively, it's hard to imagine a situation where the difference either way would be consequential, but see other more quantitative answers. Coding based on speed here is probably an example of our favorite pejorative, which can be abbrevated "pi".

Which is best?

It depends on what assertion about $str you want to confirm, and what consequence you want to invoke.

Another common pattern you'll see is

!$str

which gives generally the same result - and may be appropriate if you simply want to test for a string value that is unusable, no matter why it's unusable - which could be lack of initialization, initialization default, assignment, etc. (I'm not arguing for or against this representation, BTW.) Remember that what you decide will presumably have consequences, and you need to understand what $str states invoke which consequences, based on the way you've written the code. (And notice there are $str value/states which you might not have explicitly covered with either of our options.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文