Aug 15

For whatever reason, the ternary operator is not used very often in PHP. Hell, I didn't even know what it was until several months ago. However, it is a very useful tool. Basically, it's a short way of condensing if statements with only one result. Example:

if($_GET['variable'] == "yes"){
	$flag = true;
}
else{
	$flag = false;
}

That's 6 lines of code for something that is VERY simple. Let's look at the ternary operator version:

$flag = $_GET['variable'] == "yes" ? true : false;

One line! Much better. Let me explain how this works. When using the ternary operator, you have 3 statements, arranged like so:

[statement 1] ? [statement 2] : [statement 3]

They evaluate like this: if [statement 1] evaluates true, then [statement 2], or else [statement 3]. So, in our example, if you set the $_GET['variable'] to "yes", $flag would equal true, otherwise it is set to false. However, it's not just limited to one statement. For example:

$flag = $_GET['variable'] == "yes" ? ($_GET['variable2'] != "no" ? true : false) : false;

If $_GET['variable'] is yes, and $_GET['variable2'] isn't no, then flag is true, otherwise it is false. That would've taken a lot more code without the ternary operator, wouldn't it? Yet we managed to do it in an entire one line.

  • Digg
  • StumbleUpon
  • del.icio.us
  • Reddit

2 Responses

  1. Anonymous Says:

    Just assign it to the expression's value, for chrissakes, quit making things complicated.

    $flag = ($_GET['variable'] == "yes");

  2. admin Says:

    That was just an example; you could have all sorts of things there such as numeric values, etc. However, for this particular example, you are right, your method would be much easier.

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.