user1253538
user1253538

Reputation:

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.

I am doing this:

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

Why is this incorrect?

Upvotes: 1

Views: 495

Answers (5)

Mathieu Viau
Mathieu Viau

Reputation: 11

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

Upvotes: 1

Tom Wright
Tom Wright

Reputation: 11489

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.

Upvotes: 3

robjmills
robjmills

Reputation: 18598

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..

Upvotes: 7

Salil
Salil

Reputation: 47512

Ref this

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

Upvotes: 1

Mark Baker
Mark Baker

Reputation: 212452

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

Upvotes: 4

Related Questions