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

My Blog

Here is my awesome blog.

php – the tertiary statement

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:

((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.

4 Responses to “php – the tertiary statement”

  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