Ad space (banner)
๐Ÿ˜PHP Lessons
Lesson 15 / 68

The Ternary Operator

In this lesson you will learn PHP's ternary operator so you can express a simple branch concisely on one line. This is for anyone searching for "PHP ternary operator how to use".

condition ? valueIfTrue : valueIfFalse expresses a simple if statement on one line. It suits short decisions such as working out whether someone counts as an adult and picking a message on the spot.

The sample code uses $age >= 20 ? "Adult" : "Minor" to choose which string to assign to $message based on $age. Notice how one line replaces the four an if statement would take.

A common stumbling block for beginners is nesting ternary operators until they become unreadable. Cramming a complex condition in makes things worse, so the trick is to reserve it for simple either/or decisions. Nested ternaries are especially hard to read, so knowing when to go back to an if statement matters.

In real-world development it comes up constantly for small value choices: switching the text on screen based on a condition, or picking a default. It is often combined with the ?? operator too.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run PHP directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)