Go4Expert (http://www.go4expert.com/)
-   PHP (http://www.go4expert.com/forums/php/)
-   -   Pre-check Variable in PHP using the ternary operator (http://www.go4expert.com/forums/pre-check-variable-php-using-ternary-t9223/)

pradeep 10Mar2008 18:48

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:


Test Condition ? Code If True : Code If False

Here's a simple example:
PHP Code:

= (isset($_REQUEST['theme']))?$_REQUEST['theme']:'cool_blue';

The above line of code automagically assigns a default value if the paramter is not found.It uses the isset() function to check if $_REQUEST['theme'] exists. If $_REQUEST['theme'] does exist it simply returns its value. However, if it does not exist 'cool_blue' is returned.

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 14:16.