php 101

Combining Variables

Let's say you've got two strings and you need to combine them into a single string. We've seen one example of that already, in our URL parameters example. Here's another way the same statement could be written:

This example differs from the first one - the argument to echo() is a series of plain text strings and PHP variables, stitched together with periods (dots). The strings are enclosed in quotes and the variables are not. For now, the two methods may seem interchangeable, but as your projects grown in complexity, you'll find good reasons for using both styles.

It's also common to build a string entirely in PHP, then spit it back as a single variable, like this:

In this case, we assigned the whole concatenated string to a single variable ($greeting) and passed that as an argument to echo() instead. This technique allows you to build a string slowly as a script progresses, finally spitting back one giant (but neatly contained) variable.

Of course, you'll often need to insert chunks of HTML into your strings. With PHP, HTML code can be generated like any other string. In this example, we'll build up our string variable over multiple steps, and insert HTML while we're at it.

There's one new concept in that example - notice that we assigned a value to the $greeting variable twice. But the second time, we did it with .= instead of a single = sign. Just like we used the dot operator (period) to concatenate pieces of a string together, we can use .= to concatenate new data onto the end of an existing variable.

Can you guess what would happen if you left the dot out of the second $greeting variable assignment? Try it and see if you were right.