1

How can I create a php ternary expression containing just if statement without the else part? This is what I tried :

$vn = condition ? expression1 ; 

And this is what I'm trying to achieve

if(condition) { $vn = expression1; } 

to

$vn = condition ? expression1 ; 

3 Answers 3

3

You could use the same variable in the else part:

$vn = condition ? expression1 : $vn ; 

Note this creates a notice if $vn was not used before.

Sign up to request clarification or add additional context in comments.

2 Comments

You could use @$vn in the else part to prevent the notice.
@Barmar yes. But in fact you should initialise $vn first. Suppressing notices, warnings and errors is never a good idea.
1

If you are using PHP 7, you may want to consider the Null Coalescing Operator.

In certain cases, the syntax is similar to what you seem to be looking for:

$email = $_POST['email'] ?? 'none'; // is the same as: $email = isset($_POST['email']) ? $_POST['email'] : 'none'; 

Comments

1
(condition) AND ($vn = expression1); 

works too.

And only as info:

$v = condition?:expression1 

is also possible, here the condition (in case) is parsed to $v

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.