PHP Strings Primer - Concatenation
(Page 6 of 37 )
Concatenation gives us an easy way to splice strings together. The syntax is simple and easy to understand. Let's take a look at a simple example of how to combine two strings.
<?php $one = 'Hello'; $two = 'world'; $mystring = $one . $two; ?> |
After this code executes, '$mystring' would contain 'Helloworld'. Obviously, it would be preferable to have a space between the two words. In that case, all we need to do is a little more concatenation and we have our desired results.
<?php $one = 'Hello'; $two = 'world'; $mystring = $one . ' ' . $two; ?> |
Now, the '$mystring' variable would contain 'Hello world'.
A common use for concatenation is to combine literal strings and variables. Even though we can include the variables inside double quotes, or within the heredoc method, some developers opt to use concatenation instead. It has been argued that using a combination of single quotes and concatenation is faster than the use of double quotes and variables substitution.
After some testing, we have determined that using single quotes and concatenation is faster. In our tests, we executed each method 100,000 times. This yielded a total difference of one tenth of second for all 100,000 runs on our test machine. You may see a smaller, or larger, difference on your hardware. No matter what, the difference is very small, but in applications where efficiency is number one this could make the difference. For the fun of it, we also tested the heredoc method, and as expected it came in last at almost a tenth of a second behind the double quote method. All this performance testing is fun as an exercise, but it is unlikely that any one quoting method is going to give your application a significant performance boost.
Next: Displaying Strings >>
More Programming Basics Articles
More By Matt Wade