Small Changes to Make If Statements Easier to Scan

When developing programs with hundreds of lines of code, it's beneficial to write code that's easy to scan. That way when you need to update the program months or years later, it will be much easier to follow along. In addition to breaking the code into logical chunks, adding comments, etc. it's helpful to indent code which only gets executed given a specific criteria. For example, all the code within the if/else statement.

Let's say we have a page which displays an HTML form when the visitors first arrive. It then displays a thank you message once the form is submitted. We could write out the code as follows:

<?php
if(isset($_POST['submit'])) {
$first_name = trim($_POST['first_name']);
$last_name = trim($_POST['last_name']);
echo "Thank you $first_name $last_name, your information was received on ";
echo date('F j, Y');
} else {
echo '<form method="post" name="form" action="">';
echo '<label for="first_name">First Name:</label> ';
echo '<input type="text" name="first_name" id="first_name" /><br />';
echo '<label for="last_name">Last Name:</label> ';
echo '<input type="text" name="last_name" id="last_name" /><br />';
echo '<input type="submit" name="submit" value="Send Info" />';
echo '</form>';
}
?>

But is there anything we can do to improve the code? It's a little difficult to figure out where the "if" ends and the "else" begins. So how does it look if we indent the lines of code within the if/else.

<?php
if(isset($_POST['submit'])) {
    $first_name = trim($_POST['first_name']);
    $last_name = trim($_POST['last_name']);
    echo "Thank you $first_name $last_name, your information was received on ";
    echo date('F j, Y');
} else {
    echo '<form method="post" name="form" action="">';
    echo '<label for="first_name">First Name:</label> ';
    echo '<input type="text" name="first_name" id="first_name" /><br />';
    echo '<label for="last_name">Last Name:</label> ';
    echo '<input type="text" name="last_name" id="last_name" /><br />';
    echo '<input type="submit" name="submit" value="Send Info" />';
    echo '</form>';
}
?>

Now that's much easier to scan. Of course, you may want to adjust the number of spaces to indent each line of code. Instead of five spaces, like above, maybe you prefer a bigger indent.

Related Posts

0 Comments

There are currently no comments.

Leave a Comment