Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Use the short if-statement without else?

I'm a fan if the short if-version, example:

($thisVar == $thatVar ? doThis() : doThat());

I'd like to cut out the else-statement though, example:

($thisVar == $thatVar ? doThis());

However, it wont work. Is there any way to do it that I'm missing out?

like image 379
Philip Avatar asked Feb 14 '18 00:02

Philip


People also ask

Can we use if without else in PHP?

An if statement looks at any and every thing in the parentheses and if true, executes block of code that follows. If you require code to run only when the statement returns true (and do nothing else if false) then an else statement is not needed.

Can we have if else if without else?

You never need an else clause.

Can we write ternary operator without else?

The ternary operator is not equivalent to if/else. It's actually an expression that has to have a value. You cannot use ternary without else, but you can use Java 8 Optional class: Optional. ofNullable(pstmt).

How we use if ELSE and ELSE IF statement in PHP?

In PHP we have the following conditional statements: if statement - executes some code if one condition is true. if...else statement - executes some code if a condition is true and another code if that condition is false. if...elseif...else statement - executes different codes for more than two conditions.


2 Answers

You can't use it without the else. But you can try this:

($thisVar != $thatVar ?: doThis());

or

if ($thisVar == $thatVar) doThis();
like image 185
Wilson Madrid Avatar answered Sep 22 '22 15:09

Wilson Madrid


The ternary operator is designed to yield one of two values. It's an expression, not a statement, and you shouldn't use it as a shorter alternative to if/else.

There is no way to leave out the : part: what value would the expression evaluate to if you did?

If you're calling methods with side effects, use if/else. Don't take short cuts. Readability is more important than saving a few characters.

like image 45
John Kugelman Avatar answered Sep 22 '22 15:09

John Kugelman