Coding concisely: boolean data in PHP

In this article I describe some "shortcuts" to deal with boolean values in PHP scripts. These are standard syntax features of PHP, but novice programmers often write code that is several times longer than it needs to be. Hopefully the examples in this article can be of some help in trimming down such code and keeping it concise.

Assigning true or false to a variable

I very often see this in PHP source code:

if ($a == 5) $b = true; else $b = false;

The code works, but is somewhat cumbersome compared to the equivalent

$b = $a == 5;

At first this latter method can seem difficult to read, but it doesn't take long to get used to. What's happening is that the right hand side of the assignment ($a == 5) evaluates to true or false and is then assigned to the variable $a.

Returning true or false values

A similar technique can be applied to return values in functions. For example,

if ($a == 5) return true; else return false;

can be rewritten as

return $a == 5;

Assigning a variable to one of two values

Similarly, consider assigning a variable a non-boolean value based on a condition that can go one of two ways. For example, the following code:

if ($a == 5) $str = "\n"; else $str = "\t";

can be rewritten using the ternary operator as:

$str = $a == 5 ? "\n" : "\t";

What's happening here is that if $a == 5 evaluates to true, $str is assigned to the value after the "?", otherwise it is assigned to the value after the ":".

I find that I often write my code in the long-winded fashion first, and upon stepping back realize that I could save a few lines and tidy up the script by rewriting the code in the shorter versions instead. Other times I skip this step and write the shorter versions straight off, this being something that happens more and more as I gain experience.

Checking the value of a boolean variable inside an if statement

It is fairly common for novice programmers to write "$bool == true" inside a condition test, when it is enough to simply enter the variable name. For example, given a boolean variable $isHomePage,

if ($isHomePage == true) // do something

can be rewritten as

if ($isHomePage) // do something

The equivalent for testing for a false value is, instead of writing

if ($isHomePage == false) // do something

to write

if (!$isHomePage) // do something

In this case the "!" operator (which can be pronounced "not"), inverts the value of the $isHomePage variable, and is like saying "if not isHomePage..."

Ensuring a variable is a boolean, not another data type

In PHP, non-boolean types are automatically treated as booleans when they occur in an expression such as "$i == true", where $i might be an integer, a string, or whatever. For example, a variable of type integer evaluates to true in a test so long as its value is not zero. In these cases you might want to check if $i really is a boolean with the stricter identity ("===") operator as follows:

// check $i is a boolean evaluating to true if ($i === true) // do something // check $i is a boolean evaluating to false if ($i === false) // do something

With the code above, the first "// do something" section would only get executed if $i was a boolean that evaluated to true, and not if it was an integer, float or string of any value. There is no shorthand way of using this construct.

Combining nested if statements

The following if statements:

if ($a == 5) if ($b == 10) // do something

can be combined into

if ($a == 5 && $b == 10) // do something

The second version is more concise, using an "and" to test both conditions. If the first condition is false, the second condition is not tested, making the statement equivalent to the two separate if statements. Of course there will be times when you will want to use separate if statements, such as when there are other statements which must be executed if the first test is true, regardless of the second.

Closing thoughts

The examples above are very simple. Much more complex boolean expressions can be created, in which case it often helps to group logical units in parentheses for the sake of visual clarity and to control the precedence of operations. Also, ternary operators can be stacked on other ternary operators, though this can quickly become harder to read and also have unexpected outcomes (according to the PHP manual).

These techniques are also applicable to other languages with a similar syntax to PHP, such as C, Java and JavaScript.

if ($myVar) if ($i != 0) -----> if ($i) if ($str != '') -----> if ($str) if ($myVar = getSomething()) ... assign & test for truth at the same time -->