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";
Related
Why is this printing 2?
echo true ? 1 : true ? 2 : 3;
With my understanding, it should print 1.
Why is it not working as expected?
Because what you've written is the same as:
echo (true ? 1 : true) ? 2 : 3;
and as you know 1 is evaluated to true.
What you expect is:
echo (true) ? 1 : (true ? 2 : 3);
So always use braces to avoid such confusions.
As was already written, ternary expressions are left associative in PHP. This means that at first will be executed the first one from the left, then the second and so on.
Separate second ternary clause with parentheses.
echo true ? 1 : (true ? 2 : 3);
Use parentheses when in doubt.
The ternary operator in PHP is left-associative in contrast to other languages and does not work as expected.
from the docs
Example #3 Non-obvious Ternary Behaviour
<?php
// on first glance, the following appears to output 'true'
echo (true?'true':false?'t':'f');
// however, the actual output of the above is 't'
// this is because ternary expressions are evaluated from left to right
// the following is a more obvious version of the same code as above
echo ((true ? 'true' : false) ? 't' : 'f');
// here, you can see that the first expression is evaluated to 'true', which
// in turn evaluates to (bool)true, thus returning the true branch of the
// second ternary expression.
?>
In your case, you should consider the priority of executing statements.
Use following code:
echo true ? 1 : (true ? 2 : 3);
For example,
$a = 2;
$b = 1;
$c = 0;
$result1 = $a ** $b * $c;
// is not equal
$result2 = $a ** ($b * $c);
Are you have used parentheses in expressions in mathematics? - Then, that the result, depending on the execution priority, is not the same. In your case, ternary operators are written without priorities. Let the interpreter understand in what order to perform operations using parentheses.
Late, but a nice example for being carefull from now:
$x = 99;
print ($x === 1) ? 1
: ($x === 2) ? 2
: ($x === 3) ? 3
: ($x === 4) ? 4
: ($x === 5) ? 5
: ($x === 99) ? 'found'
: ($x === 6) ? 6
: 'not found';
// prints out: 6
Result of PHP 7.3.1 (Windows Commandline). I can not understand, why they changed it, because the code becomes really unreadable, if I try to change this.
This works:
$number = 1;
$number == 1? print 'yes' : print 'no';
but this doesn't work:
$number = 1;
$number == 1? echo 'yes' : echo 'no';
Why is this happening in PHP?
The parameters to the ternary operator have to be expressions. print 'yes' is an expression, but echo 'yes' is not, because echo is special syntax.
Use the ternary operator as the argument of echo, not the other way around.
echo $number == 1 ? 'yes' : 'no';
It's the same reason you can't write:
$var = echo 'yes';
Check your log for a warning. The ternary operator must return a value. print returns 1 always, but echo does not return a value.
Regarding your comment about putting echo in a function, functions that don't explicitly return a value return null by default, therefore, the function is indeed returning a value:
http://php.net/manual/en/functions.returning-values.php
http://php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary
http://php.net/manual/en/function.print.php
http://php.net/manual/en/function.echo.php
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;
I want to have what this would output:
if ($user->newsletter == 1) {
echo 'YES'; }
else {
echo 'NO'; }
What I have:
echo $user->newsletter == 0 ?: 'YES' ?: 'NO';
This outputs YES where it should be YES, so this is okay,
but it outputs 1 where it should be NO.
Is there a way how to write this?
Your syntax is a bit odd. This is how you typically use the ternary operator:
echo ($user->newsletter == 1) ? 'YES' : 'NO';
As of PHP 5.3 there is a new way to use the ternary operator:
$foo = $foo ?: $bar;
// which is equivalent to
$foo = $foo ? $foo : $bar;
This short hand is referred to as the Elvis operator.
In your case you can not use this shorthand as you want to transform 0 or 1 into 'Yes' or 'No'.
($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";