I was expecting the output would be:
http://domain.dev/category/123
But the actual output is: ""
$condition = true;
$categoryId = 123;
$result = 'http://domain.dev/category' . empty($condition) ? '' : '/' . $categoryId;
var_dump($result);
From what I understand - it check if empty($condition)
is empty - if true then append http://domain.dev/category
with ''
OR else /$categoryId
What did I do wrong?
The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.
In the above syntax, we have tested 2 conditions in a single statement using the ternary operator. In the syntax, if condition1 is incorrect then Expression3 will be executed else if condition1 is correct then the output depends on the condition2.
The Java ternary operator provides an abbreviated syntax to evaluate a true or false condition, and return a value based on the Boolean result. The Java ternary operator can be used in place of if..else statements to create highly condensed and arguably unintelligible code.
The ternary operator take three arguments: The first is a comparison argument. The second is the result upon a true comparison. The third is the result upon a false comparison.
just put ()
around statement:
$result = 'http://domain.dev/category' . (empty($condition) ? '' : '/' . $categoryId);
so it's treated as operator
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With