Pre-check Variable in PHP using the ternary operator
Checking whether variables are defined or not before you use them can be a tiring to incorporate into your PHP code, and this is one of the many things skipped or overlooked by a majority of PHP programmers, leading to large number of PHP Notice errors and possibly leaving the application vulnerable in some way. 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 especially useful when dealing with $_GET, $_POST, $_SESSION etc. variables, because you might not 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's a simple example:
The operator can be useful in a number of situations, and helps you to avoid loads of unnecessary if statements.
|All times are GMT +5.5. The time now is 06:07.|