If Statement in the Middle of Concatenation

if statement in the middle of concatenation?

if is a self standing statement. It's a like a complete statement. So you can't use it in between concatenetion of strings or so.
The better solution is to use the shorthand ternary operatior

    (conditional expression)?(ouput if true):(output if false);

This can be used in concatenation of strings also. Example :

    $i = 1 ;
$result = 'The given number is'.($i > 1 ? 'greater than one': 'less than one').'. So this is how we cuse ternary inside concatenation of strings';

You can use nested ternary operator also:

    $i = 0 ;
$j = 1 ;
$k = 2 ;
$result = 'Greater One is'. $i > $j ? ( $i > $k ? 'i' : 'k' ) : ( $j > $k ? 'j' :'k' ).'.';

php if/else with concatenation

You can't put an IF right in the middle of concatenating a string. Either do the IF before and pass the value where you had the IF

if ($row['msetupfee'] =='-1.00') {
$v = "N/D";
}
else {
$v = $row['msetupfee'];
}

//
// Other code
//
..."<td>" . $row['curprefix'] . " " . $v ."</td>"...

OR do this...

..."<td>" . $row['curprefix'] . " " . ($row['msetupfee'] =='-1.00' ? 'N/D' : $row['msetupfee']) . "</td>"...

How to concatenate if statement inside echo in php?

It will help to you. Try this.

<?php
$html = '';
$html .= '<div class="main">Some html</div>';
if (is_page('my-account')) {
$html .= '<div class="account_data">Some account related data</div>';
}
echo $html;

Concatenating strings with `if` statements in JavaScript

I'd use a ternary operator:

data = "<html>\n"
+ "<head>\n"
+ ( typeof metadata_title !== "undefined" ? "<title>" + metadata_title + "</title>\n" : "" )
+ ( typeof metadata_author !== "undefined" ? "<meta name=\"author\" content=\"" + metadata_author + "\"></meta>\n" : "" )
+ ( typeof metadata_date !== "undefined" ? "<meta name=\"date\" content=\"" + metadata_date + "\"></meta>\n" : "" )
+ "</head>\n"
+ "<body>\n"
+ "\n"
+ paras.join("\n\n")
+ "\n"
+ "\n"
+ "</body>\n"
+ "</html>"
;

PHP - Concatenate if statement?

Like this, using the ternary operator:

echo "<li class='". (($_GET["p"] == "home") ? "active" : "") . "'><a href='#'>Home</a>        </li>";  

Why does C not allow concatenating strings when using the conditional operator?

According to the C Standard (5.1.1.2 Translation phases)

1 The precedence among the syntax rules of translation is specified by
the following phases.6)


  1. Adjacent string literal tokens are concatenated.

And only after that


  1. White-space characters separating tokens are no longer significant. Each
    preprocessing token is converted into a token. The resulting
    tokens are syntactically and semantically analyzed and translated as a
    translation unit
    .

In this construction

"Hi" (test ? "Bye" : "Goodbye")

there are no adjacent string literal tokens. So this construction is invalid.



Related Topics



Leave a reply



Submit