Tutorial: Using Concatenation in PHP Useful for outputting logs and other stuff

Sometimes, you’ll find yourself having a lot of variables that you need to mix together. Concatenation is very handy for mixing your variables into a coherent output. A simple example of how to do concatenation:

// assign the values for the variables -- note the spacing
$introstart = "My name is ";
$firstname = "Kim ";
$lastname = "Enders";

// now we concatenate those variables and place them into a single variable, $output
$output = $introstart . $firstname . $lastname;

// lastly, we output the $output variable
echo $output;

Result:

My name is Kim Enders


A More Advanced Example

In a gaming script I have been working on, I wanted to have a logging system that showed who withdrew/deposited items from the group’s vault. Some of the code from that follows:

First, I started off with the variables I pulled with an earlier query…

       
       $userName = '' . $row['userName'] . '';
       $action = '' . $row['action'] . '';
       $itemquantity = '' . $row['itemquantity'] . '';
       $itemname = '' . $row['itemname'] . '';
       $date_pulled = '' . $row['date'] . '';

I created a new variable to indicate whether the user withdrew or deposited items. It checks the action variable and assigns the correct string accordingly.

       if($action == 'withdrew') {
       $conn = "from the Vault";
       } else {
       $conn = "to the Vault";
       }

A logging system is much more useful if you have pertinent details like when an action took place. Here, I format the date that was pulled. I add a couple of variables to handle punctuation and extra words needed to help the date’s inclusion fit into the log entry.

The concatenation comes into play on the last line of the code below when you take all of the specified variables and join them together with ‘ . ‘ in between (minus the apostrophes.)

       $date1 = date('M j', strtotime("$date_pulled"));
       $date2 = date('g:i A', strtotime("$date_pulled"));
       $date3 = date('Y', strtotime("$date_pulled"));
       $comma = ", ";
       $at = " at ";

       $date = $date1 . $comma . $date3 . $at . $date2;

Finally, I output all of the variables.

echo "$userName $action x$itemquantity $itemname $conn on $date";

The result looks like this:
An entry log for my game's vault system.

How it looks inside my game:
A vault logging system for my game

In closing, using concatenation in PHP can be incredibly useful. It’s also very easy. Hopefully this helps! If you have any questions, make sure to leave a comment below.

If you found this post useful, leave a comment below!

Leave a Reply

Your email address will not be published. Required fields are marked *