In PHP, is there a way to concatenate two strings using a ternary conditional?
<?= 'something' . (true) ? 'else' : 'not'; ?>
When I try that, all I get is else rather than the desired something else.
Just put brackets around the entire ternary operator like this:
<?= 'something' . ((true) ? ' else' : ' not'); ?>
Why do you have to do that?
The answer is: operator precedence
See the manual for more information: http://php.net/manual/en/language.operators.precedence.php
Yes, you need to put your ternary in brackets though. Try this:
<?php echo 'something '.((true) ? 'else' : 'not'); ?>
Your code is equal to
<?= ('something' . (true)) ? 'else' : 'not'; ?>
Because according to the table of Operator Precedence the operator . has higher precedence of ternary operator ?:
So, you must force the priority with parentheses as explained by Rizier123
Related
I've reviewed the PHP Manual here: #3 ternary operators
but I don't understand why all three of these don't function as expected:
$a = array('a','b','c');
//works
if(isset($a)){echo "yes";} else {echo "no";}
//works
isset($a) == true ? $answer = "yes" : $answer = "no";
echo $answer;
//does not work
isset($a) == true ? echo "yes" : echo "no";
Thank you for your consideration.
Since the ternary expression is an expression, its operands have to be expressions as well. echo is not an expression, it's a statement, it can't be used where expressions are required. So the last one doesn't work for the same reason you can't write:
$a = echo "abc";
Rewrite the statement as,
echo isset($a) == true ? "yes" : "no";
The ternary operator doesn't exactly function like an if statement. The ternary operator does not execute the 2nd or 3rd expressions, it returns it.
The correct way is:
echo isset($a) == true ? "yes" : "no";
Also no need to compare it with true:
echo isset($a) ? "yes" : "no";
Because when you use ternary operators you need to count operators precedence and associativity
you can rewrite your code to
echo isset($a) ? "yes" : "no";
Your last line of code should be like;
echo isset($a) == true ? "yes" : "no";
I am describing the problem by example:
let,
$actual_food['Food']['name'] = 'Tea';
$actual_food['Food']['s_name'] = 'Local';
I am concatenating the aforesaid variables in following way.
$food_name = $actual_food['Food']['name']." ".!empty($actual_food['Food']['s_name']) ? "- ".$actual_food['Food']['s_name'] : "";
when i print $food_name then the output like ' - Local' but does not print $actual_food['Food']['name'] content.
I think this question is very little bit silly but my curious mind wants to know. Thanks in advance.
You need to take care about concatenation while using ternary operators. You can try as
$food_name = ($actual_food['Food']['name'])." ".(!empty($actual_food['Food']['s_name']) ? "- ".$actual_food['Food']['s_name'] : "");
echo $food_name;// Tea - Local
Over here I've enclosed the variables within parenthesis ()
Its because of what we call operator precedence. If we don't enclose the ternary operator within parenthesis then your code will be interpreted like as
($actual_food['Food']['name'] . " " . !empty($actual_food['Food']['s_name']) ?...;
So you simply enclose your ternary operator for correct interpretation
Try
$actual_food['Food']['name'] = 'Tea';
$actual_food['Food']['s_name'] = 'Local';
$food_name = !empty($actual_food['Food']['s_name']) ? $actual_food['Food']['name']." - ".$actual_food['Food']['s_name'] : $actual_food['Food']['name'];
echo $food_name;
OR
Add () before and after !empty condition like
$food_name = $actual_food['Food']['name']." ".(!empty($actual_food['Food']['s_name']) ? "- ".$actual_food['Food']['s_name'] : "");
Hello I am using ternary operator to show links in case if they exist, in case if the database field is NULL I don't want to show anything. Right now it is showing 1. how I can escape this ?
echo "".(($row['photo_01']=='')? :'<li><img src="uploads/'.$row['photo_01'].'"></li>')."
If you leave the second part of the ternary operator empty, it is equivalent to this:
echo "".(($row['photo_01']=='')
? ($row['photo_01']=='') // this is duplicated
:'<li><img src="uploads/'.$row['photo_01'].'"></li>')."
More generalized:
($x ? $x : $y) === ($x ?: $y)
($row['photo_01']=='') is evaluated to be true, which is echoed out as 1, so you need to update your code to be like this:
echo "".(($row['photo_01']=='')? '' :'<li><img src="uploads/'.$row['photo_01'].'"></li>')."
Of course you could always clean it up like this:
echo "".($row['photo_01'] ? '<li><img src="uploads/'.$row['photo_01'].'"></li>' : '')."
Use empty quotes to represent null ' ', as well as put the result of the ternary in a variable then use it in the echo to prevent cofusion:
$result = ($row['photo_01']=='') ? '' :'<li><img src="uploads/'.$row['photo_01'].'"></li>';
echo $result;
What's the best, preferred way of writing if shorthand one-liner such as:
expression ? $foo : $bar
Plot twist: I need to echo $foo or echo $bar. Any crazy tricks? :)
<?=(expression) ? $foo : $bar?>
edit: here's a good read for you on the topic
edit: more to read
echo (expression) ? $foo : $bar;
The ternary operator evaluates to the value of the second expression if the first one evaluates to TRUE, and evaluates to the third expression if the first evaluates to FALSE. To echo one value or the other, just pass the ternary expression to the echo statement.
echo expression ? $foo : $bar;
Read more about the ternary operator in the PHP manual for more details: http://php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary
Great answers above, and I love when programmers ask questions like this to create clear, concise and clinical coding practices. For anyone that might find this useful:
<?php
// grabbing the value from a function, this is just an example
$value = function_to_return_value(); // returns value || FALSE
// the following structures an output if $value is not FALSE
echo ( !$value ? '' : '<div>'. $value .'</div>' );
// the following will echo $value if exists, and nothing if not
echo $value ?: '';
// OR (same thing as)
echo ( $value ?: '' );
// or null coalesce operator
echo $value ?? '';
// OR (same thing as)
echo ( $value ?? '' );
?>
References:
PHP Operators Comparison
Null Coalesce Operator
($DAO->get_num_rows() == 1) ? echo("is") : echo("are");
This dose not seem to be working for me as intended, I get an error "Unexpected T_ECHO". I am expecting it to echo either 'is' or 'are'.
I have tried it without the brackets around the conditional. Am I just not able to use a ternary operator in this way?
The $DAO->get_num_rows() returns an integer value.
The Ternary operator is not identical to an if-then. You should have written it
echo ($DAO->get_num_rows() == 1) ? "is" : "are";
It returns the value in the 2nd or 3rd position. It does NOT execute the statement in the 2nd or 3rd position.
The ternary operator should result in a value -- and not echo it.
Here, you probably want this :
echo ($DAO->get_num_rows() == 1) ? "is" : "are";
If you want to use two echo, you'll have to work with an if/else block :
if ($DAO->get_num_rows() == 1) {
echo "is";
} else {
echo "are"
}
Which will do the same thing as the first portion of code using the ternary operator -- except it's a bit longer.
The ternary operator returns one of two values after evaluating the conditions. It is not supposed to be used the way you are using it.
This should work:
echo ($DAO->get_num_rows() == 1 ? "is" : "are");
U can use
echo ($DAO->get_num_rows() == 1) ? "is" : "are";