我有3个这样的变量
$posted_on = '0';
$shared_on = '34';
$by_id = '12';
我想$owner
从上面的 3 个变量中分配一个值,这些变量的值不是0
以$posted_on
. 目前我正在这样做,但这不会打印正确的结果
$owner = $posted_on;
$owner = '0' ? $shared_on : $owner;
$owner = '0' ? $by_id : $owner;
You mixed up your operators. To do a comparison, you need to use ==
or ===
.
$owner = $posted_on;
$owner == 0 ? $shared_on : $owner;
$owner == '0' ? $by_id : $owner;
By using the =
(assignment) operator, you effectively are assigning 0
to $owner
for each statement and then checking if the result (which is always 0
, by the definition of assignment) is true.
The difference between the two is that '==' should be used to check if the values of the two operands are equal or not. On the other hand, '===' checks the values as well as the type of operands.
You can also use the ?:
operator, which will check the left-hand side for a true value (for numbers, any non-zero) and use the right-hand side only if the left-hand side is false:
$owner = $posted_on ?: ($shared_on ?: $by_id);
To write cleaner code in this case, however, I would just use the if statements. This is because you don't need to reassign $owner
to itself in the false conditions like you do in the example.
一个单一=
的分配一个值,一个双重==
或三重===
评估两个变量。
尝试这个:
$owner = $posted_on;
$owner = $owner === 0 ? $shared_on : $owner;
$owner = $owner === '0' ? $by_id : $owner;
您可以使用or
隐式类型转换的行为:
$a = 1; $b = 0; $c = 5;
$x = $a or $x = $b or $x = $c;
echo $x;
最短的方法是:
$owner = $posted_on ?: ($shared_on ?: $by_id);
如果它是-ish(任何非零数都是),则短三元运算符对左参数求值,否则对右参数求值。 ?:
true
请注意,括号是必需的,因为在 PHP 中,三元运算符是左关联的
您可以使用单线:
$owner = $posted_on == '0' ? ($shared_on == '0' ? $shared_on : $by_id) : $posted_on;
或者,如果处理数值,
$owner = $posted_on ?: ($shared_on ?: $by_id);