Troubleshooting "Unexpected T_ECHO" in ternary operator statement - php

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

Related

Why does php return the operand rather than the condition result if you use a ?? operator on one side of the condition [duplicate]

I don't understand why this happens:
$var = 'x';
var_dump($var ?? '' == 'somevalue');
It outputs string(1) "x", while one should expect bool(false).
What is the reason behind this?
To imagine a use case, think for example at:
// I want to do something only if the optional_parameter is equal to somevalue
if($_GET['optional_parameter'] ?? '' == 'somevalue') {
...
}
It's a matter of operator precedence, try:
$var = 'x';
var_dump(($var ?? '') == 'somevalue');
More: http://php.net/manual/en/language.operators.precedence.php
Plus a general advice: there is never too many parens! :) If you're not sure what is calculated first in a given language - use them!

Unexpected behaviour of "!print("1") || 1" in php

Example1:
if(!print("1") || 1){
echo "a";
}else{
echo "b";
}
Output
1b
The Example 1 is printing "1b" instead of "1a". According to me, inside if the final condition should be if(0 || 1) after solving !print("1").
But the Example 2 is printing "1a".
Example 2:
if((!print("1")) || 1){
echo "a";
}else{
echo "b";
}
Output
1a
Can you elaborate, why the or condition in the first statement didn't work.
The key thing here is to realise that print is not a function, and doesn't take arguments in parentheses - the parentheses aren't optional, they're just not part of the syntax at all.
When you write print("1"); the print statement has a single argument, the expression ("1"). That is if course just another way of writing "1" - you could add any number of parentheses and it wouldn't change the value.
So when you write print("1") || 1 the argument to print is the expression ("1") || 1. That expression is evaluated using PHP's type juggling rules as true || true which is true. Then it's passed to print and - completely coincidentally to what you were trying to print - is type juggled to the string "1".
The print statement is then treated as an expression returning true, and the ! makes it false, so the if statement doesn't run.
This is a good reason not to use parentheses next to keywords like print, require, and include - they give the mistaken impression of "attaching" an argument to the keyword.

Ternary Operator shows 1 instead on null

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;

Concatenate + Ternary

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

PHP can't take more than one ternary operator?

Basically I have the following code:
However when I var_dump $isLoggedIn and $isset($_COOKIE['access_token']) both are false (so through the ! in the <?php?> it gets true) and the href should be connect.php... but it always is main.php?auto=true".autoooooo does not even exist (I just made it for testing) and href should actually be empty.
What am I doing wrong?
In php, the ternary operator (?:) associates left-to-right (unlike in C or perl where it associates right-to-left).
That means that it evaluates the first test ? value 1 : value 2, and then uses that result to determine which value of the second operator to use.
Your construct would work in C or perl, but in php, you need to add brackets around each subsequent ternary operator.
Also, for readability, I recommend you add quite a few newlines and indents in your code.
Use brackets for your 2nd clause:
$b1 = false;
$b2 = false;
echo $b1 ? 'b1 true' : ($b2 ? 'b2 true' : 'all false') ;
Output:
all false

Categories