PHPBuilder - The Ternary Conditional Operator

RSS Twitter
Articles Application Architecture

The Ternary Conditional Operator

by: PHP Builder Staff
March 6, 2008

submitted by scross
Checking for variables before you use them can be a tedious process, and this step is often missed out in PHP code, leading to masses of PHP Notice errors and possibly leaving the application vulnerable. However, there is a simple solution to this problem, something called the ternary conditional operator. This allows you to check for the existence of a variable (or check that the variable has a valid value) and assign a value accordingly. This is very useful when you are dealing with $_GET, $_POST, $_SESSION etc. variables, because you don't know whether the incoming variable will exist, and if it doesn't you might want to assign a default value. Here is the format of the ternary conditional operator:


Here is an example to hopefully put this into context:

$id = isset($_GET['id']) ? $_GET['id'] : false;
This one line of code does a surprisingly large amount. Firstly, it uses the isset() function to check if $_GET['id'] exists. If $_GET['id'] does exist it simply returns its value. However, if it does not exist the operator returns false. The value that the operator returns is then assigned to the variable $id. So, basically, if $_GET['id'] exists then $id = $_GET['id'], however if it does not exist then $id = false
The operator can be useful in a number of applications, and helps you to avoid loads of unnecessary if statements.

Comment and Contribute

Your comment has been submitted and is pending approval.




(Maximum characters: 1200). You have characters left.