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);
}
?>
November 26th, 2005 at 10:47 am
[…] Note: I used a function in the above example called iif(). You can get this function at http://phpit.net/code/iif-function. […]
April 21st, 2006 at 11:25 am
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”))
May 13th, 2006 at 7:35 pm
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
May 25th, 2006 at 8:45 am
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.
May 25th, 2006 at 9:05 am
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.