Shorthand PHP IF statement without the else notation

Posted On Oct 21, 2008 at 9:13 pm

PHP In an earlier post I explained how to do Ternary shorthand if/else statements in PHP. One of the major benefits of using a shorthand if/else statement is that you can use it inline with a string. But what if you only need to do in inline if statement, without the else?

Most people would just do the standard shorthand notation and make the else return a blank string like this:

$string = "The car is ".($carDead==true?"NOT":"")." working.";

If you're kind of anal about how your code looks, you might not like doing this because it's redundant and makes the code less readable (not by much, but still). Doing a quick search on Google, I found that many people have asked if theres a way to do a shorthand if without the else. The straight answer is no, PHP does not offer such notation. However, I have a solution.

PHP allows you to execute functions inline with a string and the returned value of that function will be inserted into the string. We can use this to create a pseudo inline if statement. Here is the function:

function iif($statment,$returnTrue=true,$returnFalse=false) { if($statement) return $returnTrue; else return $returnFalse; }

Now you can load the function iif anytime you need to do an inline if statement without an else (but it also has the built in ability for a specified false return as well by including a third parameter)

$string = "The car is ".iif($carDead==true,"NOT")." working";

This code will not execute as quickly as a straight if/else statment, but I'm sure the performance difference is so minimal that it would not make a significant difference unless you were processing thousands of inline statements using this function.

This topic has the following tags:

Comments (6)

Post Comment

You are replying to cancel reply

Your email address will not be visible to the public

Avatars by Gravatar. Join Gravatar for free to have your avatar shown everywhere you post.