PHP: Use the short if-statement without else?
Asked Answered
T

7

18

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?

Turbellarian answered 14/2, 2018 at 0:10 Comment(4)
No there isn't a way to do it, because it isn't a short if, more of a short if/else (although even that is just a very simplistic way of looking at it)Punchy
[1,null][$thisVar==$thatVar] ?? doThis();Oversew
@mickmackusa Its not. [1, null] is a 2 element array, and [$thisVar==$thatVar] is an array accessor, which accesses element 0 if its false or element 1 if its true, and element 1 will null coalesce. onecompiler.com/php/3xr67v6w3Oversew
@chi I see now. I guess this is just another example of why commenting unexplained solutions under a question is not good for Stack Overflow and its readers. As a personal choice, I don't like to use this approach (ternaries) unless the outcome is being used/assigned.Hemphill
M
20

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

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

or

if ($thisVar == $thatVar) doThis();
Mesencephalon answered 14/2, 2018 at 0:15 Comment(0)
U
10

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.

Urine answered 14/2, 2018 at 0:13 Comment(2)
I don't fully agree. imagine: <li class="<?php echo $is_active ? 'active' : '' ?>"> vs javascript style: <li class="<?= $is_active && 'active' ?>"> vs react js: <li className={is_active && 'active'}> if you building lot of php sites and you use lot of conditional stuff like this its pain to always do the : ' ' part. Now for "readability" imagine: <li class="<?php if($is_active): echo "active"; endif; ?>"> the JS style php is the most readable one.Fumikofumitory
@ErikKubica Those expressions don't have side effects.Urine
A
2

Just use logical operators : AND, OR, &&, ||, etc.

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

a frequent use is :

$obj = doSomething($params) or throw new \Exception('Failed to do');
Argyres answered 2/9, 2022 at 15:34 Comment(0)
A
1

USE NULL TO SKIP STATEMENTS WHEN IT IS IN SHORTHAND

$a == $b? $a = 10 : NULL;
Allhallows answered 9/3, 2022 at 16:21 Comment(0)
I
0

Working for me:

$leftHand != $rightHand?doThis():null;
$leftHand == $rightHand?null:doThis();
Irony answered 11/11, 2021 at 13:0 Comment(1)
Please add some explanation to your answer such that others can learn from it. As far as I can see, your code still uses the else part, so how does this solve the given question?Dictation
I
0

hmm interesting, because executing the below code is valid. Observe:

for ($i = 1; $i <=10; $i++) {
    if ($i % 2) {
      echo $i;
    }
  }

The above code indeed, will output 13579

Notice no 'else' clause was used in the above.

If you wanted to inform the user of whether $i % 2 == FALSE ($i's divisor yielded remainder 0), you could include an else clause to print out the even numbers like shown below:

for ($i = 1; $i <=10; $i++) {
    if ($i % 2) {
      echo "$i is odd";
      echo "<br />";
    } else {
      echo "$i is even";
      echo "<br />";
    }
  }

Giving you the output: 1 is odd 2 is even 3 is odd 4 is even 5 is odd 6 is even 7 is odd 8 is even 9 is odd 10 is even

I hope my amazingly easy to understand examples will help all newcomers to PHP, hands down the 'best' server-side scripting language for building dynamic web applications :-)

Instrumentalist answered 13/12, 2021 at 13:42 Comment(0)
A
0

Here is how you should implement a short if statement without else

$side = 'Right';

($side == 'Right') ? $sideValue ='Value for Right Side':'';
Alithia answered 24/2, 2023 at 19:9 Comment(1)
this is the same as the user don't wantInfinite

© 2022 - 2025 — McMap. All rights reserved.