Reuse GET and POST Instead of Duplicating Variables

When reading data from the GET or POST array, why do we assign the information to another variable? Why can't we just use the GET or POST variables? It's not like we unset those variables after the new ones are created. Instead of duplicating variables, consider keeping the ones created for us by PHP.

Overview

Let's say we have a data-collection form where visitors can sign up to receive our newsletter. Keeping this example simple, we'll say the form only collects an e-mail address using the POST method. The code grabbing the e-mail address might look something like this:

<?php
$email = (isset($_POST['email'])) ? trim($_POST['email']) : '';
?>

The code currently tests if the POST variable has been set. If it has, the value is trimmed and assigned to $email. If it's not set, $email is still created and given an empty string. The code works perfectly fine, but is the duplicate variable needed?

A variable in the POST array already exists. We can just as easily reassign the data back to the variable.

<?php
$_POST['email'] = (isset($_POST['email'])) ? trim($_POST['email']) : '';
?>

Adding Context to Variables

As PHP scripts get longer and more intricate, the more important it becomes to add context to variables. We've all probably heard the argument for variables being named based on their purpose. It's better to store our e-mail address in a variable called $email than $a.

Well, the idea could be expanded even further to consider where the data's origin. For the past few years, I've been trying to do that with associative arrays. Information from forms, for example, might go into an array like $formRequest. So, an e-mail address would be stored as $formRequest['email'].

However, the same thing could be accomplished with reusing the POST variables. Most form processing scripts only handle data from a single form, so it should be easy to tell where the data comes from. Whenever we see a variable like $_POST['email'], it likely comes from an online form.

Conclusion

You probably won't notice much difference between scripts using duplicate variables versus not, but it's still worth making these little changes to keep our code lean. Plus, there's the added benefit of knowing more about where the data comes from.

0 Comments

There are currently no comments.

Leave a Comment


Warning: Undefined variable $user_ID in /home/cyberscorp/webdev.cyberscorpion.com/wp-content/themes/scorpbytes/comments.php on line 72