我如何切换布尔数字? [英] How can I toggle a boolean number?

查看:139
本文介绍了我如何切换布尔数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

  $ num = 1; ($ num == 1){
$ num = 0
} else {
$ num = 1; //它总是0或1


}

正如您所看到的,我的代码切换了数字。我真的很难过。我猜php应该有这样做的功能。但是在搜索后我没有发现任何类似的东西。无论如何,我可以做更多的标准和更好的吗?



我正在编写一个伟大的公司。这就是为什么我要编写干净而专业的代码。 解决方案

您的方法是正确的,并且可以正常工作。只需要将其包装到一个函数中即可。另一种方法是使用 ^(Bitwise XOR)
$ p $ 函数toggleNumber($ num){
返回$ num ^ = 1;
}



在线演示






该函数获取数字并与 1 就可以了。然后号码将被切换。


Here is my code:

$num = 1; // it always is either 0 or 1

if ( $num == 1 ){
    $num = 0
} else {
    $num = 1;
}

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 ^ (Bitwise XOR) to do that functional and more clean:

function toggleNumber( $num ) {
    return $num ^= 1;
}

Online Demo


That function gets the number and does XOR with 1 on it. Then the number will be toggled.

这篇关于我如何切换布尔数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆