Alex Rivera | Logout

PHP if shorthand

Asked 2011-06-22T23:09:45.470
20

I have a string that I want to append it some other string. let's say:

$my_string = 'Hello';

$my_string .= ' there';

this would return 'Hello there'.

I want to make this conditional like this:

$my_string = 'Hello';

$append = 'do';

if ( $append == 'do' ) {

    $my_string .= ' there';

}

Now, I want to use a ternary operation to do this, but all the examples I came across are for if/else which will be something like:

$my_string .= ( $append == 'do' ) ? ' there' : '';

so is it possible to do it with only IF and without else?

Edit
Report

2 Answers

28

Nope. However, the opposite is possible. Here's a quote from the PHP docs:

Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.

http://php.net/manual/en/language.operators.comparison.php

answered 2011-06-22T23:16:11.913
20

combining mellamokb and Andz you can do this:

( $append != 'do' ) ?: $my_string .= ' there';
answered 2011-06-22T23:21:53.033

Your Answer