1. We have moved from vBulletin to XenForo and you are viewing the site in the middle of the move. Though the functional aspect of everything is working fine, we are still working on other changes including the new design on Xenforo.
    Dismiss Notice

Pre-check Variable in PHP using the ternary operator

Discussion in 'PHP' started by pradeep, Mar 10, 2008.

  1. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,646
    Likes Received:
    86
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    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:

    Code:
    Test Condition ? Code If True : Code If False
    Here's a simple example:
    PHP:
      <?php
      
      $theme 
    = (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.
     

Share This Page