Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ternary Operator issue [duplicate]

Tags:

php

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?

like image 928
I'll-Be-Back Avatar asked Jan 19 '17 11:01

I'll-Be-Back


People also ask

Can ternary operator have 3 conditions?

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.

Can ternary operator have two conditions?

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.

Can ternary operator return True False?

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.

What are the three arguments of a ternary operator?

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.


1 Answers

just put () around statement:

$result = 'http://domain.dev/category' . (empty($condition) ? '' : '/' . $categoryId);

so it's treated as operator

like image 60
Bostjan Avatar answered Sep 21 '22 12:09

Bostjan