PHP use implode() to output array items on new lines

The other day I wanted to output a list of equipment selected from a check-box group in an email using PHP’s mail() function. The problem was I was using an array to hold the list of selected check-box items, so when I came to output the list I had no way of iterating through the array to append the items to the message. After searching through the PHP Manual I came across a page for the implode()function. This function is for joining array elements with a string. The syntax is as follows:

string implode ( string $glue , array $pieces )

The problem with the implode() function is that, in default form with no $glue parameter it will just push out a string containing the concatenated value of the array you passed through it. So even though I could now output the chk_group[] array it didn’t look very nice.
After a short time of trying different approaches to this I discovered that you can pass an escape sequence character as a $glue parameter and when the PHP interpreter parses it the escape character is added in and the output is correctly formed with new lines.

A code example of this is when considering a list of checkboxes where multiple checkboxes are checked and assigned to an array named chk_group[].


<input type="checkbox" name="chk_group[]" value="Camera" />Camera<br />
<input type="checkbox" name="chk_group[]" value="Phone" />Phone<br />
<input type="checkbox" name="chk_group[]" value="iPad" />iPad<br />
<input type="checkbox" name="chk_group[]" value="iPod" />iPod<br />


implode("\n", $_POST['chk_group']);

In this example the actual php code is in an external file to the HTML form so we grab the chk_group[] array from the $_POST variable. When building the email the idea is to explode the array with the newline \n switch so that the output appears as below:

Equipment Required:
MacBook Pro
VGA Adaptor

Jason Edwards