是否可以使用一个三元运算符设置多个变量?

编程入门 行业动态 更新时间:2024-10-09 13:31:07
本文介绍了是否可以使用一个三元运算符设置多个变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我一直在寻找是否可以使用一个三元运算符设置多个变量。我用谷歌搜索了一下,但没有提出任何建议。我开始测试一些想法,发现了一些接近的地方-但也得到了一些奇怪的行为;有什么想法吗?而且,是否可以在一个三元操作中设置多个 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

更多推荐

是否可以使用一个三元运算符设置多个变量?

本文发布于:2023-11-09 04:00:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1571344.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   可以使用   变量   运算符

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!