在关联数组中使用三元函数 (PHP)
Using Ternary Function in Associative Array (PHP)
我想了解是否可以 a) 和 b) "side-effect free" 在 PHP 中使用三元函数分配关联数组元素。
所以不是这个:
$second_element = $test ? "tistrue" : "tisfalse";
echo build_assignment_page(array(
'firstkey' => $first_element,
'secondkey' => $second_element,
'thirdkey' => $third_element
));
像这样:
echo build_assignment_page(array(
'firstkey' => $first_element,
'secondkey' => ($test ? "tistrue" : "tisfalse"),
'thirdkey' => $third_element
));
三元运算符 可以在任何允许表达式的地方使用。 (它 不是 像 if..else
或 while
这样的结构)。
因此,您的代码有效。
三元运算符从来没有副作用。它检查条件的计算结果是否为 true
或某个 true-ish 值。然后它returns一个值,取决于条件。
我想了解是否可以 a) 和 b) "side-effect free" 在 PHP 中使用三元函数分配关联数组元素。
所以不是这个:
$second_element = $test ? "tistrue" : "tisfalse";
echo build_assignment_page(array(
'firstkey' => $first_element,
'secondkey' => $second_element,
'thirdkey' => $third_element
));
像这样:
echo build_assignment_page(array(
'firstkey' => $first_element,
'secondkey' => ($test ? "tistrue" : "tisfalse"),
'thirdkey' => $third_element
));
三元运算符 可以在任何允许表达式的地方使用。 (它 不是 像 if..else
或 while
这样的结构)。
因此,您的代码有效。
三元运算符从来没有副作用。它检查条件的计算结果是否为 true
或某个 true-ish 值。然后它returns一个值,取决于条件。