ASPit - Totally ASP JSit - Totally JavaScript
Search PHPit

Use this textbox to search for articles on PHPit. Seperate keywords with a space.

Advertisements

iif function

The IIF function is a well-known function in most languages, however PHP does not contain such a function. It does now, if you include this function into your php files.

function iif($expression$returntrue$returnfalse '') {
    return (
$expression $returntrue $returnfalse);
}
?>

5 Responses to “iif function”

  1. Ezine Articles » Track your visitors, using PHP Says:

    […] Note: I used a function in the above example called iif(). You can get this function at http://phpit.net/code/iif-function. […]

  2. Mike Says:

    Can this be adapted to produce multiple options? i.e. in Access I sometimes use something like

    output = IIF(a=”1″, “I am a”, IIF(a=”2″, “I am b”, “I am c”))

  3. Gaurav Says:

    Why do we need it when a simple ternary operator already exists…

    Also, would like to know which of the “most languages” have the iif function?

    PHP: No
    C: No
    C++: No
    PERL: No
    Python: No
    Java: No
    C#: No
    Visual Basic .Net: No
    J#: No

    Or am I missing something horribly?

    -Gaurav
    http://www.edujini.in

  4. Jason Says:

    In response to Gaurav:

    Err, VB.NET *does* have an Iif function (look in Microsoft.VisualBasic), and it isn’t just a holdover from the pre-.NET days either - there’s just no other way unlike the ?: operator which exists in the C-like languages (C, C++, C#, Java, etc.). Additionally, VBA uses IIf (this shouldn’t be a surprise, since VBA is a subset of VB) which means all your Office automation products, and SQL typically has IIf and CASE function equivalents in each of its many flavours (MSAccess, MSSQL, mySQL, Oracle, etc.)

    Other than that, I agree - it can be argued that the ?: operator *is* the equivalent of an Iif function - and thus you don’t need to write your own function… the only reason I can think up is that of making code easier to read to the untrained eye.

  5. Jason Says:

    One last thought: there are cases where an operator might be preferred over a function, and vice versa.

    Functions will evaluate all arguments before executing, and ?: will perform short-circuit evaluation… this can lead to some unexpected behaviour if the arguments returntrue and returnfalse are actually the results of other function calls.

    It’s best to plug the following code in and see the difference for yourself.

Leave a Reply