PHP boolean values – shorter and semantic IFs

by Carey on November 2, 2010

Post image for 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.

Leave a Comment

Previous post:

Next post: