Ternary Conditional Operator
Maxim Maletsky on 2002 May 01
    

Many of you have probably noticed these funny question marks over the "someone's code", yet not all might have understood what do they really mean. Want to know? Well, Ternary Operator is a very common language construct for many programming languages in use today from JavaScript to C++, though, it can often be tricky to use, especially if you don't have other programming experiences besides PHP

.


How does it work?

Ternary Conditional Operator can be understood as a synonym of an IF condition. Let me give you an example to say it all:


<?php


    $username 
= isset($name)? $name $surname;


?>


In human language it would sound like this:



    If we know the value of $name, then set $username to that value. 
    Otherwise, set it to the value of $surname.



Sounds familiar? It surely it does. In fact with IF this would look like:


<?php


    
if(isset($name)) {
        
$username $name;
    }
    else {
        
$username $surname;
    }


?>


As you can see, in this very example it is easier to do a conditional operation with Ternary Operator rather than with an IF. Don't you find? Ahh, now you're interested. Follow me then.




Syntax

The syntax of Ternary Condition is quite simple itself. To give you a better idea let's decompose our previous example:


<?php


    $username 
= isset($name)? $name $surname;


?>


First you specify the action you are doing:



    [b]$username = [/b]isset($name)? $name : $surname;



Here you're defining the variable. This is optional.





    $username = [b]isset($name)[/b]? $name : $surname;



This is the condition just as it would be within an IF operator. You can add more to it with and, or, not, == , > , < and so on. In two words: if IF operator supports it - Ternary does so too. For example



    $username = [b](isset($name) and $name!='')[/b]? $name : $surname;



Note: when you have more then one condition, or any of the operators inside you should enclose the whole condition in '(' and ')'. Actually, it is always a good practice to enclose the condition between '(' and ')'.





    $username = isset($name) [b]? [/b]  $name : $surname;



This is to specify the ternary operator.





    $username = isset($name)? [b]$name[/b] : $surname;



This value will be assigned if the condition returnes True.





    $username = isset($name)? $name : [b]$surname[/b];



...and this is when it returns False.





    $username = isset($name)? $name [b]:[/b] $surname;



The column separates both values.


Additionally, you can execute sub-conditions within the returning values:


<?php


    $username 
= isset($name)? $name : ($surname$surname'User Unknown');
    
// If name is not set check whether username is set,
    // assign it if so or give default name.


?>




Things you should know

1. It is very important to understand that, no matter what will be executed on True or on False its value is what will get assigned to the variable. This is, if you use a function as one of the results, what the function returns is to be assigned.


<?php


    
function some_function($string='') {
            Return !
strlen($string)? 'unknown' $string;
    }


    
$username = isset($name)? some_function($name) : some_function($surname);
    
// Will assign 'unknown' to $username if neigher $name and $surname is set.

    
$username = isset($name)? $this =  'this' $this 'that';
    
// Will assign null to $username in both cases, but
    // will also create $this variable for you.


?>


2. You cannot execute more then one line. It would be useless as you only get one thing to do at a time.

3. With Ternary Operator you must specify the else statement, otherwise you'll get a parse error. For example:


<?php


    
echo isset($name)? $name;


?>


will not work as you might have expected. This is because the parser actually assigns the variable before it knows what the value is. In case of an if...



<?php


    
if(isset($name)) {
        echo 
$name;

}


?>


...the parser first validates the condition you set, and only if it comes true it will execute echo.



When should I use Ternary Oprators?

When you need to assign a variable or execute a function and the value conditionally differs between two cases, then it is wise using Ternary Operator. In functions it is very often seen:


<?php


    
function is_valid($password) {
        Return (
strlen($password)>=8)? True False;
    }


    echo 
is_valid($_GET['password'])? 'Passords accepted' 'Password too short!';


?>


This is how it would look without Ternary Operator:


<?php


    
function is_valid($password) {
        if(
strlen($password)>=8) {
            Return 
True;
        }
        else {
            Return 
False;
        }
    }


    if(
is_valid($_GET['password'])) {
        echo 
'Passords accepted';
    }
    else {
        echo 
'Password too short!';
    }


?>


Keep in mind...
The only reasons why you should not make an excessive usage of Ternary Operators is that you risk making you code somewhat messy. When you write an application alone this shouldn't be a problem, but if someone else will be "punished" to read it after you and, may God save his soul, even debug your code, all those ? marks might look like a scary jungle if Ternary Operators are not much of a habit.

Alright, I guess I convinced you by now (did I really?). Hope this short article can help you improve your coding style and that someday you thank me for writing it. (yeah, right...)

Maxim Maletsky
maxim@php.net
Tentatively planning to Open Soon! (no dates ...) // Doing heavy development now...