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,645
    Likes Received:
    87
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    http://blog.pradeep.net.in
    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

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice