Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP if shorthand

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?

like image 432
medk Avatar asked Jun 22 '11 23:06

medk


People also ask

How do you write short if in PHP?

We can use the ternary operator as a short-hand method of if-else condition in PHP. However, the ternary operator can be used in every other programming language. The word ternary means having three elements. So, the ternary operator has three operands.

What is short-hand if?

Else (Ternary Operator) There is also a short-hand if else, which is known as the ternary operator because it consists of three operands. It can be used to replace multiple lines of code with a single line.

What is if condition 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.

Does PHP have a ternary operator?

The term "ternary operator" refers to an operator that operates on three operands. An operand is a concept that refers to the parts of an expression that it needs. The ternary operator in PHP is the only one that needs three operands: a condition, a true result, and a false result.


1 Answers

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

like image 119
Andz Avatar answered Oct 04 '22 01:10

Andz