简体   繁体   English

在PHP中使用三元运算符

[英]Using the ternary operator in PHP

I am trying to print out yes if a boolean table field from a database query is true, and no if it is false. 如果数据库查询中的布尔表字段为true,则尝试打印yes,否则为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: 就个人而言,我从不回显HTML,所以我会这样做:

<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 "". 在您的情况下,SomeString需要为“”,后跟三进制的结果,然后为“”。 That's three strings, which need to be glued together into one string so that you can "echo()" them. 这是三个字符串,需要将它们粘合在一起成为一个字符串,以便您可以“ echo()”它们。

This is called concatenation. 这称为串联。 In PHP, this is done using a dot: 在PHP中,这是使用点完成的:

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

Which can be placed inside an echo() like this: 可以将其放置在echo()中,如下所示:

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. Sprintf()可以为您做到这一点。 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. 使用%s符号指定需要在何处插入字符串。

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

The world is now your oyster. 现在,世界就是您的牡蛎。

引用

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

由于echo需要很多参数,因此应使用逗号而不是字符串连接,因为这需要更多的处理和内存:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM