Connecting the Dots with Concatenation
Within PHP there is a consistent need to connect things together to create a new entity. Such as taking two strings and creating one string. This is usually done with variables that have a string value. The most common type of concatenation is done with strings, however you can do this with numbers but the results are not what you might expect, which would be addition of the two numbers. Instead if you concatenate the number 5 and the number 6, you do not get 11, instead you get the string "56".
When you have two variables such a one for a first name and one for a last name which is most common in form input. You may want to display a welcome message to your visitor based on their login session. To do so, you might think you would have to use either their first name or last name individually, however this would be incorrect.
There are two operators that can be used to concatenate items. They are the period "." and the period/equal operator ".=".
The "." will temporarily attach one item to the next for your current operation. The ".=" will create one item out of two instead of just temporarily attaching it to the other item.
Lets take a look at the following code:
<?php $first_name = 'Shaded'; $last_name = 'Pixel'; echo 'Hello '; //echo hello with a space after it echo $first_name; //the first name echo ' '; //echo a space echo $last_name; //the last name //the result would be: Hello Shaded Pixel //OR we could use the "period" concatenation operator echo 'Hello ' . $first_name . ' ' . $last_name; //the result would be the same as above: Hello Shaded Pixel //This way you only need one echo statement instead of four //The second way is to create a new variable using the ".=" $hello = 'Hello'; $hello .= ' '; //a space $hello .= $first_name; $hello .= ' '; //a space $hello .= $last_name; echo $hello; //result is Hello Shaded Pixel /* notice in the second example that each operator after the first assignment to $hello uses the ".=" meaning that the variable $hello, continues to obtain more and more information as the statements persist, the end result is one variable that holds the entire greeting */ //FYI: $a .= $b // is the same as $a = $a . $b; ?>
The first example of the greeting using the "." is the correct choice for this example. However, the second example using the ".=" will work. The most common use for this type of concatenation is for error messages. You can create messages throughout your script, concatenating them together using the ".=" and in the end echo out one variable that contains your error messages.
An upgrade to this idea would be to use an array of messages, and then echo out the messages from your array instead, which is a more common practice.