Looping Through Arrays
One of my favorite time saving techniques is to loop through an array whether it’s an indexed or an associative array, I’ve saved more time on projects by looping through arrays vs. writing code to handle each value of the array. I bring this up because I’ve had to update too many PHP scripts written by other developers where they handle each and every value of the $_POST or $_GET arrays as individual values to be parsed.
Here’s a practical example. It’s a good practice to remove any extra spaces from the beginning and ending of your POST values, especially before inserting that data into a database. Imagine a typical form asking for first name, last name, address (lines 1 and 2), city, state, zip and two phone numbers. I’ve seen code that has handled each one in an individual manner, but a loop can make short work of it.
Loop Example:
1 2 3 4 5 6 7 8 9 10 11 12 | <?php # look for POST array if(is_array($_POST)) { # Loop through POST array foreach($_POST as $key => $value) { # Remove whitespace and stripslashes. $_POST[$key] = stripslashes(trim($value)); } // end foreach } // end if ?> |
The individual approach would be much longer and would require editing anytime the the form was modified. Looping through the array makes it fast and uses less code making it easier to maintain, reduces the file size and much cleaner code.
As of this post, I’m currently involved in a project where there is a 3 part form, easily 30 questions or more, and each form element is handled individually. Ugh! The original developer had way too much time on their hand and didn’t make use of any looping constructs.
This methodology works for both indexed and associative arrays. Indexed arrays have numerical keys, whereas, associative arrays do not.
1 2 3 4 5 6 7 8 9 10 11 | <?php # Indexed Array $indexed[0] = "value"; $indexed[1] = "value"; $indexed[2] = "value"; #Associative Array $associative['one'] = "value"; $associative['two'] = "value"; $associative['purple'] = "value"; ?> |
Generally, I’m having to save form data into a database, and it’s really nice to be able to clean up the POST data with a loop, and at the same time include code that will build the MySQL query command on the fly. If you can, I suggest giving loops a try, especially when it comes to processing array information.
Enjoy.
