PHP Tutorial 32 of 272
Introduction & Setup
- Introduction to PHP
- History of PHP
- Features of PHP
- Applications of PHP
- Advantages and Limitations of PHP
- PHP Installation on Windows
- PHP Installation on Linux
- PHP Installation on macOS
- Setting Up a PHP Project
- Hello World in PHP
- Basic PHP Syntax
- PHP Tags and Embedding HTML
- How PHP Works on a Web Server
- PHP CLI
- PHP Configuration and php.ini
Basics
- PHP Comments
- PHP Variables
- PHP Constants
- PHP Data Types
- PHP Type Juggling
- PHP Type Casting
- PHP Strict Types
- PHP Magic Constants
- PHP Operators
- Arithmetic Operators
- Assignment Operators
- Comparison Operators
- Logical Operators
- Bitwise Operators
- String Operators
- PHP Increment and Decrement Operators
- PHP Ternary Operator
- Null Coalescing Operator
- Operator Precedence
- PHP Decision Making
- if Statement
- if-else Statement
- elseif Statement
- Nested if
- switch Statement
- match Expression
- Loops in PHP
- for Loop
- while Loop
- do-while Loop
- foreach Loop
- break Statement
- continue Statement
Functions
- PHP Functions
- User-Defined Functions
- Function Parameters
- Return Values
- Default Arguments
- Named Arguments
- Variable-Length Arguments
- Anonymous Functions
- Arrow Functions
- Callback Functions
- Recursive Functions
- Variable Functions
- Closures in PHP
- String Functions
- Math Functions
- Date and Time Functions
Arrays
- PHP Arrays
- Indexed Arrays
- Associative Arrays
- Multidimensional Arrays
- Array Iteration
- Adding and Removing Array Elements
- Sorting Arrays
- Searching Arrays
- Merging Arrays
- Array Filtering
- Array Mapping
- Array Reduction
- Array Destructuring
- Spread Operator with Arrays
- Array Functions Reference
Strings
- PHP Strings
- Single vs Double Quotes
- String Concatenation
- String Length
- String Comparison
- Substring Operations
- String Search
- String Replacement
- String Splitting and Joining
- String Formatting
- Multiline Strings
- Regular Expressions in PHP
- String Encoding and Decoding
Superglobals, Forms & Input
- PHP Superglobals
- $GLOBALS
- $_SERVER
- $_GET
- $_POST
- $_REQUEST
- $_FILES
- $_SESSION
- $_COOKIE
- Form Handling in PHP
- Form Validation
- Required Fields Validation
- Email and URL Validation
- Sanitizing User Input
- CSRF Protection
File Handling
- PHP File Handling
- fopen()
- fclose()
- fread()
- fgets()
- fwrite()
- file_get_contents()
- file_put_contents()
- readfile()
- file_exists()
- filesize()
- unlink()
- Directory Handling
- File Uploads
- Secure File Uploads
- CSV File Handling
- JSON File Handling
OOP
- Classes and Objects in PHP
- Class Properties and Methods
- Constructors
- Destructors
- Access Modifiers
- public private protected
- Static Properties and Methods
- Inheritance
- Method Overriding
- Polymorphism
- Abstract Classes
- Interfaces
- Traits
- Namespaces
- Anonymous Classes
- Final Classes and Methods
- Readonly Classes and Properties
- Magic Methods
- Object Cloning
- Dependency Injection in PHP
Error & Exception Handling
- PHP Error Reporting
- Types of PHP Errors
- Warnings and Notices
- PHP Exceptions
- try-catch
- finally Block
- throw Expression
- Custom Exceptions
- set_error_handler()
- trigger_error()
- Logging Errors
- Debugging PHP Applications
Database & MySQL
- PHP MySQL Database Introduction
- Connecting PHP to MySQL
- MySQLi Extension
- PDO in PHP
- PDO Prepared Statements
- MySQL Transactions with PHP
- CRUD with PHP and MySQL
- Insert Form Data into MySQL
- Fetch Data from MySQL
- Update Data with PHP
- Delete Data with PHP
- Pagination with PHP and MySQL
- Database Error Handling
- SQL Injection Prevention
Sessions, Cookies & Authentication
- PHP Sessions
- Starting and Destroying Sessions
- Session Security
- PHP Cookies
- Secure Cookies
- Login System in PHP
- Password Hashing
- password_hash()
- password_verify()
- Remember Me Authentication
- Role-Based Access Control
JSON, XML & APIs
- JSON in PHP
- json_encode()
- json_decode()
- Working with JSON Files
- XML in PHP
- SimpleXML
- PHP REST API
- Building a JSON API
- Consuming REST APIs
- cURL in PHP
- HTTP Headers in PHP
- API Authentication
- JWT Authentication with PHP
Security
- PHP Security Best Practices
- Input Validation vs Sanitization
- SQL Injection
- Cross-Site Scripting (XSS)
- Cross-Site Request Forgery (CSRF)
- Session Fixation
- Clickjacking Protection
- Password Security
- Secure File Uploads
- Output Encoding
- Security Headers
- Secure HTTP Cookies
Testing & Debugging
- PHP Unit Testing
- PHPUnit
- PHPUnit Assertions
- Mocking in PHPUnit
- Integration Testing PHP
- Debugging with Xdebug
- Static Analysis with PHPStan
- Code Quality with PHP CS Fixer
Composer & Packages
- Composer Introduction
- composer.json
- Composer Dependencies
- Autoloading with Composer
- PSR-4 Autoloading
- Semantic Versioning
- Publishing a PHP Package
Modern PHP
- Scalar Type Declarations
- Return Type Declarations
- Nullable Types
- Union Types
- Intersection Types
- Type Declarations and Strictness
- Nullsafe Operator
- Match Expression
- Attributes in PHP
- Enumerations (Enums)
- Readonly Properties
- Readonly Classes
- Fibers
- Generators
- Iterators
- Closures
Frameworks & Ecosystem
- Laravel with PHP
- Symfony with PHP
- PHP MVC Architecture
- Laravel Routing
- Laravel Controllers
- Laravel Eloquent ORM
- Laravel Authentication
- Symfony Components
- WordPress PHP Development
- PHP Middleware
Practice & Projects
- PHP Basic Programs
- PHP Array Programs
- PHP Function Programs
- PHP String Programs
- PHP Date Programs
- PHP Classes Programs
- PHP JSON Programs
- PHP File System Programs
- PHP Exercises
- PHP Basic Quiz
- PHP Functions Quiz
- PHP Arrays Quiz
- PHP Forms Quiz
- PHP File Handling Quiz
- PHP OOP Quiz
- PDF Downloader Project
- Automatic File Downloader
- Image Resizer Project
- File Uploader Project
- Signup Form Project
- Admin Login Project
- Group Chat Application
- PHP REST API Project
- PHP Interview Questions
- PHP Cheat Sheet
PHP Ternary Operator
Learn how the PHP ternary operator works as a shorthand for conditional statements, including syntax, nested ternary expressions, shorthand syntax, and practical examples.
On this page
- Short Ternary
- Null Coalescing
- Full Ternary
- Short Ternary
- Ternary
- if-else
- Mistake 1: Confusing ? and :
- Mistake 2: Forgetting That Ternary Returns a Value
- Mistake 3: Using Ternary for Large Blocks of Logic
- Mistake 4: Confusing ?: with ??
- Example 1: Even or Odd
- Example 2: Positive or Negative
- Example 3: Pass or Fail
- Example 4: Adult or Minor
- Conclusion
PHP Ternary Operator
The ternary operator in PHP is a conditional operator that provides a concise way to choose between two values based on a condition.
It is called the ternary operator because it takes three operands:
- A condition
- A value when the condition is true
- A value when the condition is false
The basic syntax is:
$variable = condition ? valueIfTrue : valueIfFalse;
For example:
<?php
$age = 20;
$status = $age >= 18 ? "Adult" : "Minor";
echo $status;
?>
Output:
Adult
The ternary operator is commonly used for short conditional assignments.
Ternary Operator Syntax
The general syntax is:
condition ? expressionIfTrue : expressionIfFalse;
For example:
$result = $marks >= 40 ? "Pass" : "Fail";
The condition:
$marks >= 40
is evaluated first.
If it is true:
Pass
is assigned to $result.
If it is false:
Fail
is assigned instead.
How the Ternary Operator Works
Consider:
$age = 25;
$result = $age >= 18 ? "Eligible" : "Not Eligible";
The execution can be visualized as:
$age >= 18
|
true
|
"Eligible"
If $age were 15:
$age >= 18
|
false
|
"Not Eligible"
The equivalent if-else statement is:
if ($age >= 18) {
$result = "Eligible";
} else {
$result = "Not Eligible";
}
The ternary version is shorter:
$result = $age >= 18 ? "Eligible" : "Not Eligible";
Basic Ternary Example
<?php
$number = 10;
$result = $number > 0 ? "Positive" : "Not Positive";
echo $result;
?>
Output:
Positive
If $number is -5:
Not Positive
Ternary Operator with Numbers
The ternary operator can return numeric values.
<?php
$a = 10;
$b = 20;
$max = $a > $b ? $a : $b;
echo $max;
?>
Output:
20
The condition checks whether $a is greater than $b.
If true, $a is returned.
Otherwise, $b is returned.
Ternary Operator with Strings
The operator is frequently used to select text.
<?php
$isLoggedIn = true;
$message = $isLoggedIn
? "Welcome back!"
: "Please log in.";
echo $message;
?>
Output:
Welcome back!
Ternary Operator with Boolean Values
The condition can directly use a Boolean expression.
<?php
$isAvailable = true;
$status = $isAvailable ? "Available" : "Out of stock";
echo $status;
?>
Output:
Available
Ternary Operator with if-else
A simple if-else statement:
if ($age >= 18) {
$status = "Adult";
} else {
$status = "Minor";
}
Can be written as:
$status = $age >= 18 ? "Adult" : "Minor";
Both produce the same logical result.
The ternary operator is particularly useful when each branch contains a simple expression.
Ternary Operator for Assignment
One of the most common uses is conditional assignment.
<?php
$marks = 75;
$result = $marks >= 40 ? "Pass" : "Fail";
echo $result;
?>
Output:
Pass
Instead of writing:
if ($marks >= 40) {
$result = "Pass";
} else {
$result = "Fail";
}
the ternary operator performs the assignment in one expression.
Ternary Operator Directly in echo
You can use a ternary expression directly with echo.
<?php
$age = 22;
echo $age >= 18 ? "Adult" : "Minor";
?>
Output:
Adult
No separate variable is required.
Ternary Operator in Function Arguments
A ternary expression can also be passed directly to a function.
<?php
$isActive = true;
function showStatus($status) {
echo $status;
}
showStatus(
$isActive ? "Active" : "Inactive"
);
?>
Output:
Active
Ternary Operator with Comparison Operators
The condition can use comparison operators such as:
>
<
>=
<=
==
===
!=
!==
Example:
<?php
$age = 20;
$status = $age >= 18
? "Eligible"
: "Not Eligible";
echo $status;
?>
Ternary Operator with Logical Operators
The condition can also contain logical operators.
<?php
$age = 25;
$hasId = true;
$status = ($age >= 18 && $hasId)
? "Allowed"
: "Not Allowed";
echo $status;
?>
Output:
Allowed
The condition:
$age >= 18 && $hasId
must evaluate to true for the first value to be selected.
Short Ternary Operator
PHP also supports a shortened form of the ternary operator called the Elvis operator.
The syntax is:
$value ?: defaultValue;
For example:
<?php
$name = "Gaurav";
$result = $name ?: "Guest";
echo $result;
?>
Output:
Gaurav
This is equivalent to:
$result = $name ? $name : "Guest";
The shorter form avoids repeating the same variable.
How the Short Ternary Operator Works
Consider:
$name = "";
$result = $name ?: "Guest";
Because $name evaluates to false, the result is:
Guest
If:
$name = "Gaurav";
then:
Gaurav
is returned.
The general form is:
$value ?: fallback;
Null Coalescing Operator vs Ternary Operator
PHP also provides the null coalescing operator ??.
For example:
$name = $_GET['name'] ?? "Guest";
The null coalescing operator checks whether the value exists and is not null.
Compare:
$name = $value ?: "Guest";
with:
$name = $value ?? "Guest";
They are not identical.
Short Ternary
$value ?: "Guest";
uses the fallback when $value is falsy.
Null Coalescing
$value ?? "Guest";
uses the fallback when $value is not set or is null.
For example:
$value = 0;
$result1 = $value ?: "Guest";
$result2 = $value ?? "Guest";
The results are conceptually:
$result1 → Guest
$result2 → 0
because 0 is falsy, but it is not null.
Full Ternary vs Short Ternary
Full Ternary
$result = $condition ? $valueIfTrue : $valueIfFalse;
Example:
$status = $age >= 18 ? "Adult" : "Minor";
Short Ternary
$result = $value ?: $default;
Example:
$name = $name ?: "Guest";
The short form is useful when the true value is the same variable being tested.
Nested Ternary Operator
A ternary operator can be placed inside another ternary expression.
For example:
<?php
$marks = 75;
$result = $marks >= 80
? "Excellent"
: ($marks >= 40 ? "Pass" : "Fail");
echo $result;
?>
Output:
Pass
The logic is:
marks >= 80
|
No
|
marks >= 40
|
Yes
|
"Pass"
Nested Ternary with Multiple Conditions
Another example:
<?php
$score = 85;
$grade = $score >= 90
? "A"
: ($score >= 75
? "B"
: ($score >= 50 ? "C" : "F"));
echo $grade;
?>
Output:
B
Although nested ternary expressions can be concise, deeply nested expressions can become difficult to read.
For complex conditions, if-else or switch may be clearer.
Parentheses with Nested Ternary Expressions
When using nested ternary expressions, parentheses make the intended structure clear.
Prefer:
$result = $condition1
? $value1
: ($condition2 ? $value2 : $value3);
rather than writing a long expression without clear grouping.
Modern PHP versions also discourage relying on ambiguous nested ternary expressions without explicit parentheses.
Ternary Operator with Function Calls
The values returned by a ternary expression can be function calls.
<?php
$isValid = true;
$message = $isValid
? strtoupper("valid")
: strtoupper("invalid");
echo $message;
?>
Output:
VALID
Ternary Operator with Arrays
A ternary expression can also select an array value.
<?php
$isAdmin = true;
$role = $isAdmin
? ["name" => "Admin", "level" => 1]
: ["name" => "User", "level" => 2];
print_r($role);
?>
The operator selects one of the two array expressions.
Ternary Operator in HTML
Ternary expressions are often useful in PHP templates.
<?php
$isLoggedIn = true;
?>
<h2>
<?= $isLoggedIn ? "Welcome!" : "Please log in." ?>
</h2>
If $isLoggedIn is true, the page displays:
Welcome!
Otherwise:
Please log in.
This can be useful for small conditional pieces of output.
Ternary Operator for CSS Classes
A common web-development example is conditionally selecting a CSS class.
<?php
$isActive = true;
$class = $isActive ? "active" : "inactive";
echo "<div class='$class'>Status</div>";
?>
When $isActive is true, the generated class is:
active
Ternary Operator vs if-else
Both can implement conditional logic, but they are best suited to different situations.
Ternary
$status = $age >= 18 ? "Adult" : "Minor";
if-else
if ($age >= 18) {
$status = "Adult";
} else {
$status = "Minor";
}
The ternary operator is concise and works well when the result of each branch is simple.
An if-else statement is generally easier to understand when each branch contains multiple statements.
When to Use the Ternary Operator
Use the ternary operator when:
- The condition is simple.
- Both outcomes are short expressions.
- You are selecting between two values.
- The resulting code remains easy to read.
- You need a concise conditional assignment.
Example:
$status = $isActive ? "Active" : "Inactive";
When to Avoid the Ternary Operator
Avoid using deeply nested or complicated ternary expressions.
For example:
$result = $a > 10
? ($b > 20
? ($c > 30 ? "A" : "B")
: "C")
: "D";
Although valid when correctly structured, this can be difficult to understand.
An if-else structure may be clearer:
if ($a > 10) {
if ($b > 20) {
if ($c > 30) {
$result = "A";
} else {
$result = "B";
}
} else {
$result = "C";
}
} else {
$result = "D";
}
The goal should not be to make code as short as possible. The goal is to make it clear and maintainable.
Common Mistakes
Mistake 1: Confusing ? and :
A complete ternary expression needs both parts:
$condition ? $valueIfTrue : $valueIfFalse;
For example:
$status = $age >= 18 ? "Adult" : "Minor";
Mistake 2: Forgetting That Ternary Returns a Value
The ternary operator is an expression that produces a value.
For example:
$result = $age >= 18 ? "Adult" : "Minor";
The selected value is assigned to $result.
Mistake 3: Using Ternary for Large Blocks of Logic
Avoid turning complex business logic into a single long expression.
Instead of:
$result = $condition1 ? doSomething() : ($condition2 ? doSomethingElse() : anotherFunction());
consider using a clear if-else structure when it improves readability.
Mistake 4: Confusing ?: with ??
These operators have different behavior.
$value ?: "Default";
uses the default for a falsy value.
$value ?? "Default";
uses the default when the value is not set or is null.
Ternary Operator Examples
Example 1: Even or Odd
<?php
$number = 10;
$result = $number % 2 === 0 ? "Even" : "Odd";
echo $result;
?>
Output:
Even
Example 2: Positive or Negative
<?php
$number = -5;
$result = $number >= 0 ? "Positive" : "Negative";
echo $result;
?>
Output:
Negative
Example 3: Pass or Fail
<?php
$marks = 65;
$result = $marks >= 40 ? "Pass" : "Fail";
echo $result;
?>
Output:
Pass
Example 4: Adult or Minor
<?php
$age = 16;
$result = $age >= 18 ? "Adult" : "Minor";
echo $result;
?>
Output:
Minor
Ternary Operator Quick Reference
| Syntax | Meaning |
|---|---|
$condition ? $a : $b |
Return $a if condition is true, otherwise $b |
$value ?: $default |
Return $value if truthy, otherwise $default |
$value ?? $default |
Return $value unless it is unset or null |
Example:
$status = $isActive ? "Active" : "Inactive";
Key Points to Remember
- The ternary operator is PHP's conditional operator.
- It uses three operands.
- The basic syntax is
condition ? trueValue : falseValue. - It is useful for short conditional assignments.
- The ternary operator returns a value.
- The short ternary form is
value ?: fallback. - The null coalescing operator
??is different from?:. - Ternary expressions can be nested, but excessive nesting can reduce readability.
- Parentheses should be used when they make nested expressions clearer.
- Use
if-elsewhen the logic becomes complex. - Ternary expressions are commonly used in PHP templates and conditional output.
Conclusion
The PHP ternary operator provides a concise way to perform simple conditional operations.
The standard syntax is:
$result = $condition ? $valueIfTrue : $valueIfFalse;
For example:
$status = $age >= 18 ? "Adult" : "Minor";
PHP also provides the short ternary operator:
$name = $name ?: "Guest";
and the null coalescing operator:
$name = $name ?? "Guest";
The ternary operator is most useful when the condition and both possible results are simple. For more complex logic, a clear if-else structure is usually easier to read and maintain.
Related
-
PHP Increment and Decrement Operators
Learn how PHP increment and decrement operators work, including pre-increment, post-increment, pre-decrement, post-decrement, and practical examples.
-
Conditional Statements in DSA
Learn how conditional statements help algorithms make decisions using comparisons, Boolean conditions, if-else logic, and multiple conditions.
-
Python Interview Questions and Answers
Prepare for Python interviews with commonly asked questions and answers covering Python basics, data types, functions, OOP, exceptions, collections, modules, and advanced concepts.
-
While Loop
Learn how the while loop in C repeatedly executes a block of code while a condition remains true.