PHP Tutorial: Ternary Logic, (?:) shorthand if/else

So you may have been looking through a PHP script you downloaded and seen a bit of logic that you didn’t even know was possible. What you probably saw was Ternary Logic, it had a question mark and a colon (?:) in use, making it more confusing for you. Well not any more, here comes the clarifier. The easiest way to do this is take a long hand if/else and then create a ternary logic statement to match it. So let’s try that.

<?php
/* we'll set a $gender variable, typically you will already
 have your variable set elsewhere */
$gender = 'male';
 
/* so we'll create a basic if/else */
if ( $gender == 'male' ) {
    $title = 'Mr';
} else {
    $title = 'Mrs';
}
echo $title;
/* that makes sense right? */
/* we can shorten that easily, using ternary logic */
$title = ($gender == 'male' ? 'Mr' : 'Mrs');
echo $title;
/* Also instead of putting our result into a variable, we can just
as easily put it in-line with our code, if we want to */
echo  "Hello " .($gender == 'male' ? 'Mr' : 'Mrs'). ". Smith, how are you?";
/* in our case this will output: "Hello Mr. smith, how are you?" */
 
?>

So as you can see the ternary logic form, if you were to read it as english, would read something like “$title gets the value of ‘Mr’ if $gender is equal to male, and ‘Mrs’ if $gender is not male.”

“Ok, that’s fine, but what if I want to return a true or false value?” Well that’s even easier! Let’s try it:

<?php
/* explicitly tell PHP to return a true or false */
$result = (1+1==2 ? true : false);
 
/* or imply that you want a true or false like so: */
$result = (1+1==2);
echo ($result ? '$result is true' : '$result is false');
 
?>

The above second example $result will set $result to have the return value of the expression (1+1==2) which, as far as I know is true.

And there we go, a very basic example of ternary logic, practice makes you better, so practice lots. I hope you found this helpful.

Author: Mike on April 1, 2011
Category: PHP, Tutorials
Tags: , , , ,

One thought on “PHP Tutorial: Ternary Logic, (?:) shorthand if/else”

  1. Dolly says:

    Excellent breakdown of the topic, you should write for me too!

Comments are closed.

Last articles