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?
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With