简体   繁体   English

哪个会更快,哪个是正确的PHP,而if和integer呢?

[英]Which would be faster and which is correct php while inside if and integers?

I have 2 while loops in an if then else if statement, the code works and all is good, but just a little question. 我在if then else if语句中有2个while循环,代码可以正常工作,一切都很好,但是只是一个小问题。

Take my first example, I declare on the while loop the true statement for it to execute, 以我的第一个示例为例,我在while循环上声明要执行的真实语句,

if ($levelChange > 0) {
    while ($levelChange != 0) {
        echo '<p>You gained a level you are now ' . ($levelChange + $user['level']) . '</p>';
        $levelChange--;
    }
}
elseif ($levelChange < 0) {
    while ($levelChange != 0) {
        echo '<p>You just lost a level you are now ' . ($levelChange + $user['level']) . '</p>';
        $levelChange++;
    }
}

And my second example I don't, 我的第二个例子不是

if ($levelChange > 0) {
    while ($levelChange) {
        echo '<p>You gained a level you are now ' . ($levelChange + $user['level']) . '</p>';
        $levelChange--;
    }
}
elseif ($levelChange < 0) {
    while ($levelChange) {
        echo '<p>You just lost a level you are now ' . ($levelChange + $user['level']) . '</p>';
        $levelChange++;
    }
}

They both work but which one is better to use and why, also if anyone knows which could be faster please enlighten me, 它们都可以工作,但是哪个更好用,为什么呢,如果有人知道哪个可以更快,请赐教我,

Thanks 谢谢

PHP converts its arguments to boolean values where a conditional statement is expected. PHP将其参数转换为需要条件语句的布尔值。 For numbers every non-zero value ( != 0 ) evaluates to true. 对于数字,每个非零值( != 0 )都计算为true。 The PHP docs for the boolean type have a table with conversion rules for different types. 布尔类型的PHP文档具有一个表,其中包含不同类型的转换规则。

Therefore, if($x) is equivalent to if($x == TRUE) . 因此, if($x)等同于if($x == TRUE) There isn't any (measurable) performance difference between the two forms. 两种形式之间没有任何(可衡量的)性能差异。

In this case I would say it's your preference. 在这种情况下,我会说这是您的偏好。 I would probably use the comparison to 0, but that is just my preference because it is slightly more verbose to someone else reading your code. 我可能会将比较值设为0,但这只是我的偏爱,因为它对其他阅读您的代码的人更为冗长。 There shouldn't be much a change in performance either way. 无论哪种方式,性能都不会有太大变化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM