Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

using ternary operator

if(isset($_POST["username"])) {
        $username = $_POST["username"]; 
        } else {
         $username = "";
        }
        if(isset($_POST["password"])) {
        $password = $_POST["password"];
        } else {
        $password = "";
        }

vs

// I don't know what's happening down here.
$username = isset($_POST['username']) ? $_POST['username'] : "";
$password = isset($_POST['password']) ? $_POST['password'] : "";

echo "{$username}: {$password}";

So what't he difference?

1 Answer

isset($_POST['username'])

In your example, this is asking the question "Is $_POST['username'] set?" and this part is known as the "condition".

?

Conditional Operator

$_POST['username'] : "";

This is giving two outcomes. The left of the colon will be the result if the logic results in true. The right will be the result if the logic results in false

//Example resulting in true
$a = 1;
$b = 1;
$result = $a === $b ? true : false;
//Example resulting in false
$a = 1;
$b = 2;
$result = $a === $b ? true : false;
//Example returning false
$result = isset($a) ? "this exists!" : "it does not exist!";
//Example returning true
$a = 1;
$result = isset($a) ? "this exists!" : "it does not exist!";

So as you can see, using a ternary operator is a shorthand way to do a standard "if else" statement. They are considered harder to read, so only use them when they are appropriate and not too complex.

Examples David Walsh example, and another example from stack overflow