Chris Nizzardini, Salt Lake City Utah, Web Developer Specializing in LAMP+Ajax Since 2006

My Blog

Here is my awesome blog. You can find information on programming, linux, documentation, tips for code and database optimization, my thoughts and rants, and whatever else I feel like sharing. Feel free to contribute to the blog by posting comments and asking questions.
Programming

PHP Tertiary Statement – Using Tertiaries in PHP

So Wednesday I started my new job as a php developer. It’s been way awesome so far. One of the neat things I learned is the tertiary statement/operator which looks something like this ((condition_to_test)?if_true_do_this:if_false_do_this);. Here’s an example:

1
((isset($_POST[something]))?yes:no);

If the the above statement is true then it returns a yes, otherwise it returns a no. Can’t really think of a good example for it, but it works kind of like an IF statement, especially when you just need to test something boolean-like style.

No related posts.

Tags: ,

4 Responses to “PHP Tertiary Statement – Using Tertiaries in PHP”

  1. josh says:

    lots of good uses,basically just shortens the if/else stmt…
    $msg = ($userId != “” ? “Welcome $userName” : “put login link here”);

    Just sets your welcome msg to their user name if they are logged, and would display a link to the login page if not logged in.

  2. daws says:

    ‘secret123′,
    ‘matt’ => ‘passw3rd’,
    ‘john’ => ‘rainbow33&^’
    );

    $user = ‘daws’;
    $pass = ‘secret123′;

    $loggedIn = array_key_exists($user, $userTable) && $userTable[$user] == $pass;

    echo $loggedIn ? “You are logged in as $user!” : “You have provided and invalid user/pass combo.”;
    ?>

  3. daws says:

    The previous post had php tags, which your server didn’t like.
    Here is the code:
    // Checks user/pass combo against hash table
    $userTable = array(
    ‘daws’ => ‘secret123′,
    ‘matt’ => ‘passw3rd’,
    ‘john’ => ‘rainbow33&^’
    );

    $user = ‘daws’;
    $pass = ‘secret123′;

    $loggedIn = array_key_exists($user, $userTable) && $userTable[$user] == $pass;

    echo $loggedIn ? “You are logged in as $user!” : “You have provided and invalid user/pass combo.”;

  4. admin says:

    Another great use for this is inside an echo. For instance:

    echo ‘Hello, ‘.(($_SESSION[user]==”)?’you are not logged in, please login to view this content.’:$_SESSION[user].’, thank your for logging in today’);

    Thats free hand code, but you get the idea.

Leave a Reply