我如何切换布尔数字? [英] How can I toggle a boolean number?
问题描述
这是我的代码:
$ num = 1; ($ num == 1){
$ num = 0
} else {
$ num = 1; //它总是0或1
}
正如您所看到的,我的代码切换了数字。我真的很难过。我猜php应该有这样做的功能。但是在搜索后我没有发现任何类似的东西。无论如何,我可以做更多的标准和更好的吗?
我正在编写一个伟大的公司。这就是为什么我要编写干净而专业的代码。 解决方案
您的方法是正确的,并且可以正常工作。只需要将其包装到一个函数中即可。另一种方法是使用 该函数获取数字并与 Here is my code: As you see, my code toggles the number. It is really ugly to me. I guessed php should has a function to do so. But I didn't find anything similar after some searches. Anyway, can I do that more standard and better? Currectly I'm coding for a great company. That's why I want to write clean and professional codes. Your approach is correct and will work as well. Just you need to wrap it into a function. Another way is using
That function gets the number and does XOR with 这篇关于我如何切换布尔数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! ^(Bitwise XOR)$ c
$ p $ 函数toggleNumber($ num){
返回$ num ^ = 1;
}
在线演示
1
就可以了。然后号码将被切换。$num = 1; // it always is either 0 or 1
if ( $num == 1 ){
$num = 0
} else {
$num = 1;
}
^ (Bitwise XOR)
to do that functional and more clean: function toggleNumber( $num ) {
return $num ^= 1;
}
Online Demo
1
on it. Then the number will be toggled.