Condensing if() Constructs to Improve the Scanability of Your Code

In a previous post, we went through the typical setup for the if() construct. The good thing (or bad) is that there's a lot of freedom when it comes to writing code. You could for example write the entire if() construct that contains dozens of lines of code and never use a line break. You could, but I wouldn't necessarily recommend it. However, there are other non-"standard" ways of writing out your if() constructs.


When writing code, there's a good chance that you or another developer will need to modify that script down the road. Maybe you'll need to fix a bug, update outdated code, implement a new feature, etc. These types of things don't typically happen while the code is fresh in your mind, so you'll need to re-familiarize yourself with the inner workings of the program. In addition to the standard ways of making your code easy to follow along with such as using comments, it's helpful to write code that's easy to scan.


Let's say we have multiple if/elseif components in our script that are used to initialize a couple variables:

if($verified) {
     $pgTitle     = 'Thank You';
     $buttonLabel = '';
} elseif($firstSubmit) {
     $pgTitle     = 'Verify Info';
     $buttonLabel = 'Submit';
} else {
     $pgTitle     = 'Initial Form';
     $buttonLabel = 'Continue';

Alternate Format

The above format works perfectly fine, but since the if() construct is relative short and each component essentially does the same thing, we could condense the code, making it easier to scan.

if($verified)        { $pgTitle='Thank You';    $buttonLabel=''; }
elseif($firstSubmit) { $pgTitle='Verify Info';  $buttonLabel='Submit'; }
else                 { $pgTitle='Initial Form'; $buttonLabel='Continue'; }

In addition to squishing the lines of code, you may notice that the variables have been lined up. This helps to visually indicate that they belong together.

Related Posts


There are currently no comments.

Leave a Comment