How to Write a PHP Ternary Operator

How to write a PHP ternary operator

A Ternary is not a good solution for what you want. It will not be readable in your code, and there are much better solutions available.

Why not use an array lookup "map" or "dictionary", like so:

$vocations = array(
1 => "Sorcerer",
2 => "Druid",
3 => "Paladin",
...
);

echo $vocations[$result->vocation];

A ternary for this application would end up looking like this:

echo($result->group_id == 1 ? "Player" : ($result->group_id == 2 ? "Gamemaster" : ($result->group_id == 3 ? "God" : "unknown")));

Why is this bad? Because - as a single long line, you would get no valid debugging information if something were to go wrong here, the length makes it difficult to read, plus the nesting of the multiple ternaries just feels odd.

A Standard Ternary is simple, easy to read, and would look like this:

$value = ($condition) ? 'Truthy Value' : 'Falsey Value';

or

echo ($some_condition) ? 'The condition is true!' : 'The condition is false.';

A ternary is really just a convenient / shorter way to write a simple if else statement. The above sample ternary is the same as:

if ($some_condition) {
echo 'The condition is true!';
} else {
echo 'The condition is false!';
}

However, a ternary for a complex logic quickly becomes unreadable, and is no longer worth the brevity.

echo($result->group_id == 1 ? "Player" : ($result->group_id == 2 ? "Gamemaster" : ($result->group_id == 3 ? "God" : "unknown")));

Even with some attentive formatting to spread it over multiple lines, it's not very clear:

echo($result->group_id == 1 
? "Player"
: ($result->group_id == 2
? "Gamemaster"
: ($result->group_id == 3
? "God"
: "unknown")));

How to use ternary operator in echo statement in php

You don't write ternaries directly into the string, you need to insert it into the string sort of like a variable, like this:

echo "<option value='1' ".$qty == 1? 'selected' : ''." >1</option> ";

Notice how I broke the string with before the ternary with ", added a period to concatenate the ternary, ending with another period at the end of the ternary, and started the string again with another ".

You can find more detail about this at the PHP manual: String Operations


Alternatives

Seperate ternary from string

I usually use curly braces to concatenate strings into other strings, if your echo statement is surrounded by double quotes (not single quotes), you can use this method

I would have written this with the ternary seperate from the actual string, like this:

$selected = $qty == 1? 'selected' : '';
echo "<option value='1' {$selected}>1</option>";

OR you could drop the curly brackets, but I find this less readable, and harder to tell where variables are. The string also must be wrapped in double quotes.

$selected = $qty == 1? 'selected' : '';
echo "<option value='1' $selected>1</option>";

Using Commas

You can also do string separation by commas:

$selected = $qty == 1? 'selected' : '';
echo "<option value='1'", $selected, ">1</option>";

Alternatively,

echo "<option value='1'", $qty == 1? 'selected' : '', ">1</option>";

How to replace if statement with a ternary operator ( ? : )?

The

(condition) ? /* value to return if condition is true */ 
: /* value to return if condition is false */ ;

syntax is not a "shorthand if" operator (the ? is called the conditional operator) because you cannot execute code in the same manner as if you did:

if (condition) {
/* condition is true, do something like echo */
}
else {
/* condition is false, do something else */
}

In your example, you are executing the echo statement when the $address is not empty. You can't do this the same way with the conditional operator. What you can do however, is echo the result of the conditional operator:

echo empty($address['street2']) ? "Street2 is empty!" : $address['street2'];

and this will display "Street is empty!" if it is empty, otherwise it will display the street2 address.

PHP Ternary operator ('shorthand' if-statement)

Since the ternary expression is an expression, its operands have to be expressions as well. echo is not an expression, it's a statement, it can't be used where expressions are required. So the last one doesn't work for the same reason you can't write:

$a = echo "abc";

How to write php ternary operator with array value

Yes. If you really want to use a ternary, it is possible like this:

$catId ? $clauses[] = "`category`=$catId" : null;

Here the assignment happens in the true portion of the ternary instead of assigning the result of the ternary.

Using a ternary is kind of pointless, though, because you don't want to do anything if the variable is empty, so the false portion of the ternary is irrelevent. A shorter version that should have basically the same effect is:

$catId && $clauses[] = "`category`=$catId";

Personally, I think the way you already have it is more readable and friendlier to anyone who has to work on this later by being less weird and hacky, but it is possible.

ternary operator in php with echo value

Use this code

echo (isset($options['footer_txt_color'])) ? $options['footer_txt_color'] : '#ffffff';

Ternary Operator in a php print?

Your code is being evaluated left to right. You have to enclose that ternary clause in parentheses to ensure it is evaluated before being appended to the string.

print'<span class="mailbox-attachment-icon"><i class="fa fa-'. ($extension == 'zip' ? 'yes' : 'no')  .'"></i></span>';

Using Ternary Operator In Echo Statement

Here is a reworking of the one liner with the addition of two variables to test the code such that a true result concatenates "active" to "item". A false result leads to "item" being concatenated with an empty string, as follows:

<?php
$month_number = "08";
$month_year = "2016";

echo "<div class=\"item";

// making the ternary expression more manageable
$month_result = ($month_number === "09");
$year_result = ($month_year === "2017");
echo ($month_result && $year_result)? "active":"";

echo "\"></div>";

Live code here

Note: if you wish to do one echo statement you could code as follows:

$str =  ($month_result && $year_result)? "active":"";
echo "<div class=\"item" . $str . "\"></div>";

See live code here

While you could use double quotes for attributes and single quotes for everything else, it is easier to see escaped double quotes for attributes, i.e. \" and double quotes for the outer strings.



Related Topics



Leave a reply



Submit