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;
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
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
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";