PHP ternary operator expecting colon and semicolon [duplicate] - php

This question already has answers here:
Troubleshooting "Unexpected T_ECHO" in ternary operator statement
(4 answers)
Closed 3 years ago.
This ternary operator within an element is giving an error:
<div class="col-sm<?php $columnCasecheck === true ? echo '-3' : echo '-4' ?>">
PhpStorm is expecting a colon after true ? and a semicolon after '-3'. Why is that? It seems like a valid ternary operator to me. See screenshot.

Try this:
<?php echo $columnCasecheck === true ? '-3' : '-4'; ?>
Inside the ternary you should put value or expression, instead of commands.
So the echo should be outside the ternary expression.
Also, if you don't need strict comparison, you can just write:
<?php echo $columnCasecheck ? '-3' : '-4'; ?>
So your whole line will be:
<div class="col-sm<?php echo $columnCasecheck ? '-3' : '-4'; ?>">

Take your echo out of an expression as follows -
<?php echo $columnCasecheck === true ? '-3' : '-4'; ?>

Since you want to output the result, just put the echo in front of the expression:
echo $columnCasecheck === true ? '-3' : '-4';

How about this?
<?php $columnCasecheck = $columnCasecheck === true ? '-3' : '-4'; ?>
<div class="col-sm<?=$columnCasecheck?>>value</div>

Related

What means this line? [duplicate]

This question already has answers here:
How to replace "if" statement with a ternary operator ( ? : )?
(16 answers)
Closed 3 years ago.
$n = isset($_GET["n"]) ? $_GET['n'] : '';
I find this "method" to avoid errors before insert stuff in the input type.. and it works.. but I would like a detailed explanation of this line. Thank you!
This is called the ternary operator shorthand of if...else
(condition) ? true : false
There is a condition which has been checked on left, if its true the statement after the ? will be execute else the statement after the : will execute.
It's called Ternary operator
The ternary operator is a shorthand for the if {} else {} structure. Instead of writing this:
if ($condition) {
$result = 'foo'
} else {
$result = 'bar'
}
You can write this:
$result = $condition ? 'foo' : 'bar';
If this $condition evaluates to true, the lefthand operand will be assigned to $result. If the condition evaluates to false, the righthand will be used.
In your case
If the value of $_GET["n"] isset then it'll take $_GET["n"] value.
if the value is not set then it'll take ('') value.
$n = isset($_GET["n"]) ? $_GET['n'] : '';

How to use if and else inside echo statement? [duplicate]

This question already has answers here:
How to write a PHP ternary operator [duplicate]
(10 answers)
Closed 5 years ago.
I've heard something about ternary operator but I kind of beginner and don't know how to use it, I'm trying to make this:
echo '<div>
'.if(LoginCheck($this->db) == true):.'
<span class="option1"></span>
'.else:.'
<span class="option1"></span>
'.endif;.'
</div>';
Yes the ternary operator is what you're looking for, but you have to chain them to get the if-else statement.
echo '<div>'.(LoginCheck($this->db) == true ?
'<span class="option1">' : '<span class="option2"></span>').'</div>'
The evaluation statement comes before the question mark (?) and there is no if tag to put before the statement. It's just the expression to evaluate to true/false, and then the question mark, and then the first statement is if the expression is truthy, the second statement, separated from the first by a colon (:), is if the expression is not truthy.
Look here for some more info.
echo '<div>
'.((LoginCheck($this->db)) ? '
<span class="option1"></span>
' : '
<span class="option1"></span>
').'</div>';
Article about PHP ternary operator
As much i understand you cannot use 'if-else' statement in 'echo'. You have to use reverse. You can use your 'echo' in 'if-else' statement. Below code might help you:
$html = "&ltdiv&gt";
if(LoginCheck($this->db) == true){
$html .= "&ltspan class='option1'>&lt/span>";
}else{
$html .= "&ltspan class='option2'>&lt/span>";
}
$html .= "&lt/div>";
echo $html

how to nest if and else statement using ternary operator in PHP?

am confused with using this ternary operator, i can easily get 1 level if and else
e.g
($blah == $blah) ? blahblah : blahblahblah;
but what if the condition is like this?
if($blah == blah1)
{
echo $blah1;
}
else if($blah == blah2)
{
echo $blah2;
}
else
{
echo $blah;
}
how to convert this using ternary operator ?
<?php echo $blah == 'blah1' ? $blah1 : ($blah == 'blah2' ? $blah2 : $blah); ?>
Notice how the else is wrapped in parenthesis. This can be done again and again, although it becomes confusing to read.
Nested ternaries are a bad idea. They're provided for brevity. If you have nested conditions, you by definition do not have brevity.
Some folk don't even like their use when you have a concise statement. Personally I find the following more clear and readable than the if-based alternative.
echo $success ? 'Success' : 'Failure';
But I would hesitate to do anything more complex than that.
($blah == $blah1) ? $blah1 : (($blah == $blah2) ? $blah2 : $blah);
It would become:
echo (($blah == $blah1) ? $blah1 : (($blah == blah2) ? $blah2 : $blah);

error object and array

I have this code
$myvar = is_object($somevar) ? $somevar->value : is_array($somevar) ? $somevar['value'] : '';
issue is that sometime I am getting this error
PHP Error: Cannot use object of type \mypath\method as array in /var/www/htdocs/website/app/resources/tmp/cache/templates/template_view.html.php on line 988
line 988 is the above line I included. I am already checking if its object or array, so why this error then?
It has something to do with priority, or the way PHP is evaluating your expression. Grouping with parentheses solves the problem:
$myvar = is_object($somevar) ? $somevar->value : (is_array($somevar) ? $somevar['value'] : '');
See the notes here: http://www.php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary
Note:
It is recommended that you avoid "stacking" ternary expressions. PHP's
behaviour when using more than one ternary operator within a single
statement is non-obvious:
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.
?>
You need to place parenthesis around the second ternary:
$myvar = is_object($somevar) ? $somevar->value : (is_array($somevar) ? $somevar['value'] : '');
This must have something to do with operator precedence, though I'm not sure why yet.
Opinion: The ternary with or without parenthesis is difficult to read IMHO. I'd stick with the expanded form:
$myvar = '';
if(is_object($somevar)) {
$myvar = $somevar->value;
} elseif(is_array($somevar)) {
$myvar = $somevar['value'];
}

Simple PHP issue

I'm new to shorthand conditional statements and I can't for the life of me work out how to do it, here's the simple code I have:
<?php
function evolve_nav($vals) {
echo '<'.$vals['type'] !== '' ? ''.$vals['type'].'' : 'darn''>';
}
?>
Does anyone know why this doesn't return anything and results in an error?
You just forgot some brackets:
function evolve_nav($vals) {
echo '<'.(!empty($vals['type']) ? $vals['type'] : 'darn').'>';
}
evolve_nav(array('type' => 'foobar'));
evolve_nav(array('not' => 'showing'));
echo '<' . ($vals['type'] !== '' ? $vals['type'] : 'darn') .'>';
$descriptiveVariableName = $vals['type']!=='' ? $vals['type'] : 'darn';
// View code
echo "<$descriptiveVariableName>";
''.$vals['type'].'' is superfluous, make it $vals['type']
'darn''>' those are two string literals without any operator (or anything) between them -> syntax error.
In this case I'd rather not use string concatenation (i.e. using the dot-operator like 'xyz' . $a ) but "pass" multiple parameters to echo.
echo
'<',
''!==$vals['type'] ? $vals['type'] : 'darn',
'>';
or using printf
printf('<%s>', ''!==$vals['type'] ? $vals['type'] : 'darn');

Categories