Log Online Form Requests Part 2: Add the Field Separator Dynamically with implode()

When saving data to text files, each field is usually separated by something like the pipe character (|). The character is useful for importing and dividing the fields into a spreadsheet solution like Microsoft Excel. Normally, I add the character between each field manually, but there's an alternate using PHP's implode() function.

Overview

Last week's post (Log Online Form Requests in Case Something Happens with the E-mailed Results) provided a solution for backing up requests from online forms. However, I've never been entirely happy with coding strings which contain a lot of variables. Especially when those variables are derived from associative arrays. For example, let's look at the variables from last week:

<?php
$formRequest['name']    = 'John Smith';
$formRequest['address'] = '426 1st St., New York, NY 10453';
$formRequest['email']   = 'test@gmail.com';
?>

To prepare the variables for the text file, my normal process was to embed them into the string as follows:

<?php
$forTextFile = date('Y-m-d') . "|$formRequest[name]|$formRequest[address]|$formRequest[email]";
var_dump($forTextFile);
?>

It looks nicer in my opinion, but it's problematic if we need to search for all occurrences of the name variable, for example. Some cases will have quotes around the array key ($formRequest['name']) and others won't. To improve the searchability of my code, I've been switching between the following solutions:

<?php
$forTextFile = date('Y-m-d') . '|' . $formRequest['name'] . '|' . $formRequest['address'] . '|' . $formRequest['email'];
var_dump($forTextFile);
 
$forTextFile = date('Y-m-d') . "|{$formRequest['name']}|{$formRequest['address']}|{$formRequest['email']}";
var_dump($forTextFile);
?>

Both options look okay when there's only a few variables to work with. It gets a little messy, however, when there's dozens of them.

Alternate Solution

Well, as with everything in the programming world, there is another way. Instead of embedding the variables directly into the string, let's store them in an array. The implode() function could then be employed to dynamically add the field separator.

<?php
$forTextFile_fieldArray = array(date('Y-m-d'), $formRequest['name'], $formRequest['address'], $formRequest['email']);
$forTextFile = implode('|', $forTextFile_fieldArray);
var_dump($forTextFile);
?>

Conclusion

Although this may seem like a silly adjustment to make, I find it's much easier to grasp what's going. There's also no need to worry about whether the separator character was included between each field or if the proper separator was used. The values still need to be separated with a comma, of course, but it's a little easier without the string getting in the way.

0 Comments

There are currently no comments.

Leave a Comment