Using Concatenation with PHP Variables
Yesterday I introduced PHP variables and demonstrated how they can be set and used by means of a simple example. Today I want to expand on this and show how you can use concatenation to use multiple variables in the same line of code to create more complex and dynamic strings.
In PHP, the concatenation symbol is the period symbol as shown at the end of this sentence -> .
<?php $stringVariable = "My lucky number is"; $integerVariable = 11; print $stringVariable . " " . $integerVariable; ?>
A string and an integer variable are set as demonstrated in the “How to use Variables in PHP” article. The difference this time comes in the print function which uses concatenation to combine the variables into a single sentence.
In the above example, it is not enough to simply concatenate the two variables or else the final result printed would be, “My lucky number is11″. To avoid this problem we could add a space to the end of our $stringVariable but this could cause a new bug if for example we wanted to use the variable at the end of a sentence with a period following directly after. The best way to solve the problem is to therefore use concatenation to add an empty space between both variables when they are printed. The way to do this is shown in the above example by using the set of quotes with a space between them.
November 26th, 2007 at 1:04 pm
[...] Using Concatenation with PHP Variables [...]