2

我有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;
4

5 回答 5

1

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.

(http://www.geeksww.com/tutorials/web_development/php_hypertext_preprocessor/tips_and_tricks/difference_between_equal_and_identical_comparison_operators_php.php)

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.

于 2013-02-21T13:08:06.553 回答
1

一个单一=的分配一个值,一个双重==或三重===评估两个变量。

尝试这个:

$owner = $posted_on;
$owner = $owner === 0 ? $shared_on : $owner;
$owner = $owner === '0' ? $by_id : $owner;
于 2013-02-21T13:09:33.590 回答
1

您可以使用or隐式类型转换的行为:

$a = 1; $b = 0; $c = 5;
$x = $a or $x = $b or $x = $c;

echo $x;
于 2013-02-21T13:11:41.343 回答
1

最短的方法是:

$owner = $posted_on ?: ($shared_on ?: $by_id);

如果它是-ish(任何非零数都是),则短三元运算符对左参数求值,否则对右参数求值。 ?:true

请注意,括号是必需的,因为在 PHP 中,三元运算符是左关联的

于 2013-02-21T13:12:55.783 回答
0

您可以使用单线:

$owner = $posted_on == '0' ? ($shared_on == '0' ? $shared_on : $by_id) : $posted_on;

或者,如果处理数值,

$owner = $posted_on ?: ($shared_on ?: $by_id);
于 2013-02-21T13:09:28.867 回答