Introduction
PHP provides shorter ways to handle simple conditions and default values. The ternary operator (?:) selects a result based on whether a condition is true or false. The null coalescing operator (??) returns a fallback value when a variable or expression is missing or evaluates to null. In this chapter, you will practise both operators through PHP Ternary and Null Coalescing Operators Practice Questions with solutions using student records, employee data, shopping calculations, and common programming situations.
Question 1: Check Whether a Student Passed or Failed Using the Ternary Operator
Problem Statement
Write a PHP program that stores a student’s marks and uses the ternary operator to display Pass if the marks are 40 or above. Otherwise, display Fail.
PHP Solution
<?php
$marks = 75;
$result = ($marks >= 40) ? "Pass" : "Fail";
echo $result;
?>
Sample Output
Pass
Explanation
The ternary operator checks whether $marks >= 40 is true.
Its syntax is:
condition ? value_if_true : value_if_false;
Since the student’s marks are 75, the condition is true, so PHP assigns "Pass" to $result.
If the marks were 30, the program would display Fail.
Concepts Covered
- Ternary operator (
?:) - Comparison operators
- Conditional expressions
- Variables and strings
Question 2: Check Whether a Person Is Eligible to Vote
Problem Statement
Create a PHP program that stores a person’s age and uses the ternary operator to determine whether the person is eligible to vote. For this example, assume the minimum voting age is 18.
PHP Solution
<?php
$age = 20;
$message = ($age >= 18)
? "Eligible to vote"
: "Not eligible to vote";
echo $message;
?>
Sample Output
Eligible to vote
Explanation
The condition $age >= 18 checks whether the person’s age is at least 18.
Because $age is 20, the condition evaluates to true, and PHP returns "Eligible to vote".
If the age were 16, the program would display "Not eligible to vote".
Concepts Covered
- Ternary operator
- Comparison operators
- Age validation
- Conditional result assignment
Question 3: Assign an Employee Bonus Status
Problem Statement
A company considers employees eligible for a performance bonus if their performance score is at least 80. Write a PHP program that uses the ternary operator to display the employee’s bonus eligibility status.
PHP Solution
<?php
$employeeName = "Rahul";
$performanceScore = 88;
$bonusStatus = ($performanceScore >= 80)
? "Eligible for Bonus"
: "Not Eligible for Bonus";
echo "Employee: " . $employeeName . "\n";
echo "Performance Score: " . $performanceScore . "\n";
echo "Bonus Status: " . $bonusStatus;
?>
Sample Output
Employee: Rahul
Performance Score: 88
Bonus Status: Eligible for Bonus
Explanation
The ternary operator checks whether the employee’s performance score is at least 80.
Since the score is 88, PHP assigns "Eligible for Bonus" to $bonusStatus.
This type of conditional expression is useful for displaying short status messages in employee reports.
Concepts Covered
- Ternary operator
- Employee data
- Comparison operators
- String concatenation
- Conditional status assignment
Question 4: Apply a Shopping Discount Using the Ternary Operator
Problem Statement
A store offers a 10% discount when a customer’s purchase amount is ₹5,000 or more. Otherwise, no discount is applied. Write a PHP program to calculate the discount and final bill amount.
PHP Solution
<?php
$purchaseAmount = 6000;
$discountRate = ($purchaseAmount >= 5000) ? 10 : 0;
$discountAmount = ($purchaseAmount * $discountRate) / 100;
$finalAmount = $purchaseAmount - $discountAmount;
echo "Purchase Amount: ₹" . $purchaseAmount . "\n";
echo "Discount Rate: " . $discountRate . "%\n";
echo "Discount Amount: ₹" . $discountAmount . "\n";
echo "Final Amount: ₹" . $finalAmount;
?>
Sample Output
Purchase Amount: ₹6000
Discount Rate: 10%
Discount Amount: ₹600
Final Amount: ₹5400
Explanation
The ternary operator checks whether the purchase amount is at least ₹5,000.
If the condition is true, $discountRate becomes 10. Otherwise, it becomes 0.
The program then calculates the discount amount and subtracts it from the original purchase amount.
Concepts Covered
- Ternary operator
- Percentage calculations
- Shopping bill calculations
- Arithmetic operators
- Conditional values
Question 5: Provide a Default Username Using the Null Coalescing Operator
Problem Statement
Write a PHP program that checks whether a username is available. If the username is null or the variable is not defined, display Guest as the default username.
PHP Solution
<?php
$username = null;
$displayName = $username ?? "Guest";
echo "Welcome, " . $displayName;
?>
Sample Output
Welcome, Guest
Explanation
The null coalescing operator (??) returns the left-hand value if it exists and is not null. Otherwise, it returns the right-hand fallback value.
Here, $username is null, so PHP uses "Guest".
If $username contained "Amit", the output would be:
Welcome, Amit
The ?? operator can also check an undefined variable without producing the usual undefined-variable warning.
Concepts Covered
- Null coalescing operator (
??) - Default values
- Null handling
- Variables
- String concatenation
Question 6: Display a Default Department for an Employee
Problem Statement
An employee record may not contain a department value. Write a PHP program that uses the null coalescing operator to display the employee’s department. If the department is missing or null, display Not Assigned.
PHP Solution
<?php
$employee = [
"name" => "Priya",
"department" => null
];
$department = $employee["department"] ?? "Not Assigned";
echo "Employee: " . $employee["name"] . "\n";
echo "Department: " . $department;
?>
Sample Output
Employee: Priya
Department: Not Assigned
Explanation
The $employee array stores an employee’s name and department.
The null coalescing operator checks $employee["department"]. Because its value is null, PHP uses "Not Assigned" instead.
This is useful when working with company records, database results, and employee information where some fields may be empty or unavailable.
Concepts Covered
- Null coalescing operator
- Associative arrays
- Default values
- Handling null array values
- Employee records
Question 7: Display a Default Website Theme
Problem Statement
A website allows users to select a theme. If the theme is not provided or is null, use light as the default theme. Write a PHP program using the null coalescing operator.
PHP Solution
<?php
$selectedTheme = null;
$theme = $selectedTheme ?? "light";
echo "Selected Theme: " . $theme;
?>
Sample Output
Selected Theme: light
Explanation
The null coalescing operator checks whether $selectedTheme contains a non-null value.
Since its value is null, PHP uses "light" as the default.
If $selectedTheme contained "dark", the program would display Selected Theme: dark.
Remember that an empty string is not the same as null. For example, if $selectedTheme = "", the null coalescing operator returns the empty string rather than "light".
Concepts Covered
- Null coalescing operator
- Default configuration values
- Null versus empty string
- Variable assignment
- Website settings
Question 8: Set Default Values for Multiple Employee Details
Problem Statement
An employee record contains a name, department, and city. Some values may be missing or null. Use the null coalescing operator to provide suitable default values.
PHP Solution
<?php
$employee = [
"name" => "Aman",
"department" => null,
"city" => "Delhi"
];
$name = $employee["name"] ?? "Unknown";
$department = $employee["department"] ?? "Not Assigned";
$city = $employee["city"] ?? "Not Provided";
echo "Employee Name: " . $name . "\n";
echo "Department: " . $department . "\n";
echo "City: " . $city;
?>
Sample Output
Employee Name: Aman
Department: Not Assigned
City: Delhi
Explanation
The program uses the null coalescing operator separately for each employee field.
The name and city contain values, so PHP uses them. The department is null, so PHP uses "Not Assigned".
If a key does not exist in the array, the operator can also return the specified fallback without an undefined array-key warning.
Concepts Covered
- Null coalescing operator
- Associative arrays
- Multiple default values
- Employee data handling
- Missing array keys
Question 9: Combine Ternary and Null Coalescing Operators
Problem Statement
Create a PHP program that reads an employee’s performance score and optional employee name. If the name is missing or null, use Unknown Employee. Use the ternary operator to determine whether the employee passed the performance target of 75.
PHP Solution
<?php
$employeeName = null;
$performanceScore = 82;
$name = $employeeName ?? "Unknown Employee";
$status = ($performanceScore >= 75)
? "Target Achieved"
: "Target Not Achieved";
echo "Employee: " . $name . "\n";
echo "Performance Score: " . $performanceScore . "\n";
echo "Status: " . $status;
?>
Sample Output
Employee: Unknown Employee
Performance Score: 82
Status: Target Achieved
Explanation
This program uses both operators for different purposes.
The null coalescing operator provides a fallback name if $employeeName is null or undefined. The ternary operator checks whether the performance score is at least 75 and selects the appropriate status.
Combining these operators can make simple business logic shorter and easier to read.
Concepts Covered
- Ternary operator
- Null coalescing operator
- Employee performance data
- Default values
- Combining conditional operators
Question 10: Calculate Employee Net Salary with Default Allowances
Problem Statement
Create a PHP program that calculates an employee’s net salary using basic salary, allowances, and deductions.
Use these rules:
- If DA is missing or
null, use ₹0. - If HRA is missing or
null, use ₹0. - If PF is missing or
null, use ₹0. - Calculate net salary using the formula:
Net Salary = Basic Salary + DA + HRA − PF
Use the null coalescing operator to handle optional salary components.
PHP Solution
<?php
$employee = [
"name" => "Neha",
"basicSalary" => 30000,
"DA" => 2000,
"HRA" => null,
"PF" => 1800
];
$basicSalary = $employee["basicSalary"] ?? 0;
$da = $employee["DA"] ?? 0;
$hra = $employee["HRA"] ?? 0;
$pf = $employee["PF"] ?? 0;
$netSalary = $basicSalary + $da + $hra - $pf;
echo "Employee: " . $employee["name"] . "\n";
echo "Basic Salary: ₹" . $basicSalary . "\n";
echo "DA: ₹" . $da . "\n";
echo "HRA: ₹" . $hra . "\n";
echo "PF: ₹" . $pf . "\n";
echo "Net Salary: ₹" . $netSalary;
?>
Sample Output
Employee: Neha
Basic Salary: ₹30000
DA: ₹2000
HRA: ₹0
PF: ₹1800
Net Salary: ₹30200
Explanation
The program stores employee salary details in an associative array.
The null coalescing operator assigns zero to any salary component that is missing or null. Since HRA is null, $hra becomes zero.
PHP then calculates the net salary:
30000 + 2000 + 0 - 1800 = 30200
This approach helps prevent calculations from failing when optional salary components are unavailable.
Concepts Covered
- Null coalescing operator
- Associative arrays
- Employee salary calculations
- Default numeric values
- Arithmetic operations
- Handling missing data
Key Takeaways
- The ternary operator (
?:) is a compact alternative to a simpleif-elsestatement. - Its syntax is
condition ? value_if_true : value_if_false. - The null coalescing operator (
??) provides a fallback when the left-hand value is missing ornull. - The ternary operator checks a condition, while the null coalescing operator specifically handles missing or null values.
- An empty string (
""), zero (0), andfalseare not the same asnull. - The
??operator can help avoid undefined-variable and undefined-array-key warnings when checking optional values. - You can combine both operators to write concise business logic.
- Use clear variable names and avoid deeply nested ternary expressions because they can be difficult to understand.
- Validate user input before using it in salary, billing, or other important calculations.
Frequently Asked Questions (FAQs)
1. What is the ternary operator in PHP?
The ternary operator (?:) is a short way to choose between two expressions based on a condition. It returns one value when the condition is true and another when it is false.
2. What is the null coalescing operator in PHP?
The null coalescing operator (??) returns the left-hand value if it exists and is not null. Otherwise, it returns the fallback value on the right.
3. What is the difference between ?: and ?? in PHP?
The ternary operator evaluates a condition and chooses between two expressions. The null coalescing operator checks whether the left-hand value is missing or null before using a fallback.
4. What happens if a variable is undefined when using ???
PHP can use the fallback value without producing the usual undefined-variable warning. For example, $name = $username ?? "Guest"; assigns "Guest" if $username is undefined or null.
5. Does the null coalescing operator treat an empty string as null?
No. An empty string is not null, so "" ?? "Guest" returns the empty string. If you want a fallback for empty strings and other false-like values, the shorthand ternary operator (?:) may be appropriate, depending on your requirements.
6. What is the shorthand ternary operator in PHP?
The shorthand ternary operator omits the middle expression. For example, $name = $input ?: "Guest"; returns $input if it evaluates as true; otherwise, it returns "Guest".
7. Can we use ternary and null coalescing operators together?
Yes. You can use ?? to supply a default value and then use ?: to evaluate a condition. For example: $name = ($input ?? "") ?: "Guest";.
8. Which PHP version supports the null coalescing operator in PHP?
The null coalescing operator (??) was introduced in PHP 7.0. It is available in PHP 7 and later versions.
9. Which PHP version supports the ternary operator?
The ternary operator has been available since early PHP versions. It is supported in modern PHP versions, including PHP 7 and PHP 8.
10. When should I use the ternary operator instead of if-else?
Use the ternary operator for short conditions that return one of two values. Prefer if-else when the logic involves several statements, multiple branches, or complex conditions that would make the ternary expression difficult to read.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
