我一直在寻找是否可以使用一个三元运算符设置多个变量。我用谷歌搜索了一下,但没有提出任何建议。我开始测试一些想法,发现了一些接近的地方-但也得到了一些奇怪的行为;有什么想法吗?而且,是否可以在一个三元操作中设置多个 var ?如果是这样,是否有适当的方法呢?
I was looking to see if it's possible to set multiple variables with one ternary operator. I google'd a bit, but didn't come up with anything. I started testing a few ideas, and found something close -- but also getting some strange behavior; any ideas as to what's going on? And, is it possible to set more than one var in a single ternary operation? If so, is there a proper way of doing it?
$i=9; ($i==9)?($w=3|$r=2):($w=7|$r=1); echo 'w= '.$w.' r= '.$r;//w= 3 r= 2 $i=9; ($i==9)?($w=4|$r=2):($w=7|$r=1); echo 'w= '.$w.' r= '.$r;//w= 6 r= 2 $i=9; ($i==9)?($w=3|$r=7):($w=7|$r=1); echo 'w= '.$w.' r= '.$r;//w= 7 r= 7 $i=444; ($i==9)?($w=4|$r=2):($w=7|$r=1); echo 'w= '.$w.' r= '.$r;//w= 7 r= 1 $i=444; ($i==9)?($w=4|$r=2):($w=1|$r=1); echo 'w= '.$w.' r= '.$r;//w= 1 r= 1谢谢...
编辑:
我做了一些测试,发现它可以正常工作:
I did a little more testing, and found that this works correctly:
($i==9)?($w=4 AND $r=7):($w=7 AND $r=1);但是,我不确定这是否正确。而且我对第一个示例中发生的事情感到好奇。
however, I'm not sure if this is correct. And I'm curious as to what's going on in the first example.
推荐答案正如查德威克(Chadwick)解释的那样,使用 AND 或 OR 逻辑运算符将无法按照您希望的方式工作:
As Chadwick has explained, using the AND or OR logical operators will not work the way you want them to:
$i = 0; $w = 0; $r = 0; ($i==9) ? ($w=4 AND $r=7) : ($w=7 AND $r=1); echo "w = $w, r = $r\n"; // w = 7, r = 1 $i = 0; $w = 0; $r = 0; ($i==9) ? ($w=0 AND $r=7) : ($w=0 AND $r=1); echo "w = $w, r = $r\n"; // w = 0, r = 0但是,如果您真的想在一个语句中有多个分配,您可以使用 列表 构造:
However, if you really want to make multiple assignments in one statement, you can use the list construct:
$i = 0; $w = 0; $r = 0; ($i==9) ? (list($w, $r) = array(4, 7)) : (list($w, $r) = array(7, 1)); echo "w = $w, r = $r\n"; // w = 7, r = 1 $i = 0; $w = 0; $r = 0; ($i==9) ? (list($w, $r) = array(0, 7)) : (list($w, $r) = array(0, 1)); echo "w = $w, r = $r\n"; // w = 0, r = 1更多推荐
是否可以使用一个三元运算符设置多个变量?
发布评论