DevChunks

PHP boolean values – shorter and semantic IFs

This is a simple one but I am all for making code neater, tidier and more readable.

If you are using a boolean value for evaluating an IF statement, you would typically:

{code type=php}
$valid = true;
if ($valid == true)
{
# do something
}
else
{
# do something else
}{/code}

A shorter and more readable (try saying it out loud in pseudo code) method would be:

{code type=php} if ($valid)
{
# do something
} {/code}And to test for false:

{code type=php} if (!$valid)
{
# do something
} {/code}

A basic one, but I find the little touches make a big difference.

Share:

Leave a Reply

Your email address will not be published.

More Posts

How to use PHP Type Declarations

PHP has developed into a more strictly typed language in recent years. Type Declarations help with that and are a fairly new addition to PHP,

Iteration

If you have come to JavaScript from a background in Java or C, then you will like the variation on the for loop. It is

Context Object Manipulation

One of the key concepts of JavaScript is the keyword this, which signifies the JavaScript context object. If you write an inner function, you can access

Polymorphic Functions

It is possible to define multiple functions with the same name in JavaScript, and the last one of those that you define will be the