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")));
Answer from random_user_name on Stack Overflow
Top answer
1 of 10
132

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")));
2 of 10
12

Since this would be a common task I would suggest wrapping a switch/case inside of a function call.

function getVocationName($vocation){
    switch($vocation){
        case 1: return "Sorcerer";
        case 2: return 'Druid';
        case 3: return 'Paladin';
        case 4: return 'Knight';
        case 5: return 'Master Sorcerer';
        case 6: return 'Elder Druid';
        case 7: return 'Royal Paladin';
        default: return 'Elite Knight';
    }
}

echo getVocationName($result->vocation);
🌐
Matt Stauffer
mattstauffer.com › blog › even-shorter-ternary-operators-in-php-using
Even shorter ternary operators in PHP using ?: | MattStauffer.com
September 3, 2013 - A brief refresher: The PHP ternary operator allows you to write single-line comparisons, replacing code like the following: <?php if (isset($value)) { $output = $value; } else { $output = 'No value set.'; } with this: <?php $output = isset($value) ?
Discussions

Using ternary and null coalescing operators in PHP
I would prefer using a loop because it makes it clearer what is happening. The long list of nested operators might be hard to scroll through: foreach(["key1", "key2", "key3"] as $key) { $cityName = $cityName ?: ($addressArray[$key] ?? null); } This makes it clear that you are just going through a bunch of possible sources of the city. More on reddit.com
🌐 r/PHP
30
18
July 17, 2021
I think the ternary operator would be more readable if the order was reversed
Python does something similar: a = b if condition else c But I feel like it's less readable. A lot of people hate the ternary operator because they think it's not very readable, but I'm quite fond of it. If things get long I type it like: a = Condition ? b : c Which I find to be perfectly readable. Oh well. More on reddit.com
🌐 r/ProgrammingLanguages
57
0
June 20, 2024
Ternary operators are the worst..unless you indent them right!
Ternarys are amazing if you don't nest them. Just make a variable for the contents or use an if statement. More on reddit.com
🌐 r/ProgrammerHumor
328
3215
September 4, 2022
Could the null coalescing or ternary operator be improved to allow expressions?
Oh dear lord no. That's ugly as hell. Worse, it reminds me of the old days of: $con = mysql_connect(...) or die("Cannot connect to DB"); More on reddit.com
🌐 r/PHP
27
1
December 3, 2019
🌐
GeeksforGeeks
geeksforgeeks.org › php › php-ternary-operator
PHP | Ternary Operator - GeeksforGeeks
July 12, 2025 - The use of the ternary operator makes the code simpler. Example 1: In this example, if the value of $a is greater than 15, then 20 will be returned and will be assigned to $b, else 5 will be returned and assigned to $b.
🌐
PHP
php.net › manual › en › language.operators.php
PHP: Operators - Manual
= Not and = And xor = Xor or = Or 10.string Operator . = concatenation operator .= concatenating assignment operator 11.Type Operator instanceof = instanceof 12.Ternary or Conditional operator ?: = Ternary operator 13.Null Coalescing Operator ??" = null coalescing 14.Clone new Operator clone new = clone new 15.yield from Operator yield from = yield from 16.yield Operator yield = yield 17.print Operator print = print
🌐
Codementor
codementor.io › community › ternary operator in php | how to use the php ternary operator
Ternary Operator in PHP | How to use the PHP Ternary Operator | Codementor
July 19, 2019 - Statement 2: It is the statement to be executed if the condition results in a false state. Example program to whether student is pass or fail: <?php $marks=40; print ($marks>=40) ?
🌐
Stitcher
stitcher.io › blog › shorthand-comparisons-in-php
Shorthand comparisons in PHP | Stitcher.io
Examples would be 0 or '0', an empty array or string, null, an undefined or unassigned variable, and of course false itself. All these values will make the ternary operator use its righthand operand.
Find elsewhere
🌐
W3Schools
w3schools.com › php › php_if_shorthand.asp
PHP if Shorthand
zip_close() zip_entry_close() zip_entry_compressedsize() zip_entry_compressionmethod() zip_entry_filesize() zip_entry_name() zip_entry_open() zip_entry_read() zip_open() zip_read() PHP Timezones · ❮ Previous Next ❯ · To write shorter code, you can write if statements on one line. One-line if statement: $a = 5; if ($a < 10) $b = "Hello"; echo $b Try it Yourself » · if...else statements can also be written in one line, but the syntax is a bit different. One-line if...else statement: $a = 13; $b = $a < 10 ? "Hello" : "Good Bye"; echo $b; Try it Yourself » · This technique is known as Ternary Operators, or Conditional Expressions.
🌐
FlatCoding
flatcoding.com › home › php ternary operator: how to write short expressions
PHP Ternary Operator: How to Write Short Expressions - FlatCoding
July 1, 2025 - PHP checks the condition. It returns one value if the condition has a true result. It returns another value if the result is false and avoids multiple lines for if-else. ... This assigns ‘Adult’ if $age is 18 or more. It assigns ‘Minor’ if not. Use the ternary operator to make simple choices.
🌐
PixemWeb
pixemweb.com › home › php › php ternary operator explained
PHP Ternary Operator Explained - PixemWeb
February 5, 2021 - The result from the example above will just be red and not the full string you intended to output. The reason for is because of the order of operations, remember PEMDAS. In order to ensure we can output our full string with the result of the ternary operator, we have to use parenthesis. It comes down to how PHP ...
🌐
Envato Tuts+
code.tutsplus.com › home › coding fundamentals
Crash Course in the PHP Ternary Operator With Examples | Envato Tuts+
May 27, 2021 - First of all, let’s go through the following if-else example. It’s a very simple if-else statement which checks if the $_GET['limit'] variable is set, and if it’s set, initializes the $limit variable with the value of the $_GET['limit'] variable. Otherwise, it sets the $limit variable to 10. Now, let’s see what the above snippet looks like with the ternary operator.
🌐
Brj
en.php.brj.cz › ternary-operators-in-php---condition-in-one-line
Ternary operators in PHP (?:) - condition in one line
The ?: operator works like the ... face with Elvis hair, for example. The ?: operator has worked since PHP 7. In older versions, we have to make do with the if (...) condition, which can achieve the same behavior.
🌐
SitePoint
sitepoint.com › blog › php › using the php ternary operator
Using the PHP Ternary Operator
February 12, 2024 - Consisting of three parts, the ternary operator uses three expressions separated by a question mark and a colon. The question mark follows the test expression and can be thought of as asking, “Well, is it true?” The colon then separates your two possible values, the first of which will be chosen if the test expression is true, and the second if the test expression is false. Observe: <?php $message = ($coolFactor >= 10) ?
🌐
W3Schools
w3schools.com › c › c_conditions_short_hand.php
C Short Hand If ... Else (Ternary Operator)
C Date C Random Numbers C Macros C Organize Code C Storage Classes C Bitwise Operators C Fixed-width Integers ... C Examples C Real-Life Examples C Exercises C Quiz C Code Challenges C Compiler C Syllabus C Study Plan C Interview Q&A C Certificate ... There is also a short-hand if...else, known as the ternary operator because it uses three operands.
🌐
Abeautifulsite
abeautifulsite.net › posts › how-to-use-the-php-ternary-operator
How to use the PHP ternary operator
Consider this: if ($start) { $start = $start; } else { $start = 1; } Granted, you probably wouldn't do that in your code. You'd probably do something like this instead: ... But that's still three lines of code.
🌐
PHP Tutorial
phptutorial.net › home › php tutorial › php ternary operator
PHP Ternary Operator
April 6, 2025 - <?php $path = '/about'; $url = $path ?: '/'; echo $url; // /aboutCode language: HTML, XML (xml) ... Technically, you can chain ternary operators by using parentheses. Suppose you want to show various messages if users are eligible and have enough credit. The following example chains two ternary operators:
🌐
Dino Cajic
dinocajic.com › home › programming › php — p27: ternary operator
PHP Ternary Operator - PHP Conditional Operators
February 6, 2023 - Ternary operators are also great when you need to assign values to a variable after some decision is made. <?php $money = 2000; $isBuyingAMountainBike = ( $money >= 2000 ) ?
🌐
Reddit
reddit.com › r/php › using ternary and null coalescing operators in php
r/PHP on Reddit: Using ternary and null coalescing operators in PHP
July 17, 2021 - This is how for example you can send smaller 'POST'/'UPDATE' calls only mentioning the fields you actually want to be modified instead of the whole set. If you null conditional check everything, you lose the ability to know if the calling client of your function wants to update or leave the field as is. https://www.php.net/manual/en/function.array-key-exists.php#refsect1-function.array-key-exists-examples
🌐
W3Schools
w3schools.com › cpp › cpp_conditions_shorthand.asp
C++ Short Hand If Else (Ternary Operator)
Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, Python, PHP, Bootstrap, Java, XML and more.
🌐
Wikipedia
en.wikipedia.org › wiki › Binary_operation
Binary operation - Wikipedia
December 3, 2025 - Binary operations are sometimes written using prefix or postfix notation, both of which dispense with parentheses. They are also called, respectively, Polish notation ... For example, scalar multiplication in linear algebra. Here ... Ternary operation – Mathematical operation that combines three elements to produce another element