I'd like to understand if it's a) possible and b) "side-effect free" to assign associative array elements using a ternary function in PHP.
So instead of this:
$second_element = $test ? "tistrue" : "tisfalse";
echo build_assignment_page(array(
'firstkey' => $first_element,
'secondkey' => $second_element,
'thirdkey' => $third_element
));
Something like this:
echo build_assignment_page(array(
'firstkey' => $first_element,
'secondkey' => ($test ? "tistrue" : "tisfalse"),
'thirdkey' => $third_element
));
The ternary operator can be used everywhere where an expression is allowed. (It is not a construct like if..else
or while
).
Therefore, your code is valid.
The ternary operator never has side effects. It checks if the condition evaluates to true
or some true-ish value. Then it returns a value, depending on the condition.