开发者

Using the ternary operator in PHP

开发者 https://www.devze.com 2023-01-05 16:37 出处:网络
I am trying to print out yes if a boolean table fiel开发者_StackOverflow中文版d from a database query is true, and no if it is false.

I am trying to print out yes if a boolean table fiel开发者_StackOverflow中文版d from a database query is true, and no if it is false.

I am doing this:

echo "<td>"{$row['paid'] ? 'Yes' : 'No'";}</td>";

Why is this incorrect?


echo "<td>".(($row['paid']) ? 'Yes' : 'No')."</td>"; 

Personally, i never echo HTML so i would do this:

<td><?=(($row['paid']) ? 'Yes' : 'No')?></td>

Just a preference thing though..


echo "<td>".(($row['paid']) ? 'Yes' : 'No')."</td>"; 


Other guys have corrected your mistake, but I thought you might like to know why.

Your use of a ternary isn't actually the problem, it's the way you join it to the other stuff.

Echo is a function that takes one variable; a string. It's actually this (although people tend to leave the brackets off):

echo(SomeString);

In your case, SomeString needs to be "" followed by the outcome of your ternary, followed by "". That's three strings, which need to be glued together into one string so that you can "echo()" them.

This is called concatenation. In PHP, this is done using a dot:

"<td>" . (($row['paid']) ? 'Yes' : 'No') . "</td>"

Which can be placed inside an echo() like this:

echo("<td>" . (($row['paid']) ? 'Yes' : 'No') . "</td>");

Alternatively, you can skip concatenation by using a function that takes more than one string as a parameter. Sprintf() can do this for you. It takes a "format" string (which is basically a template) and as many variable strings (or numbers, whatever) as you like. Use the %s symbol to specify where it needs to insert your string.

sprintf("<td>%s</td>",(($row['paid']) ? 'Yes' : 'No'));

The world is now your oyster.


Ref this

echo "<td>".(($row['paid']) ? 'Yes' : 'No')."</td>"; 


Since echo takes many arguments, should use comma instead of string concatenation which takes more processing and memory:

echo "<td>", (($row['paid']) ? 'Yes' : 'No'), "</td>";

0

精彩评论

暂无评论...
验证码 换一张
取 消