Quakenet/#php Tutorial

Note: If you opened this page from an external URL pay attention that all chapters are linked together. Be sure you also read all prior chapters of this tutorial, otherwise you will miss relevant content explained before.

Concatenation operator

  1. Concatenate of strings and variables

1. Concatenate of strings and variables

One operator of php is the concatenation operator which is written as a single dot (.). It is used to concatenate two expressions.

'John'.'Doe'// generate a string "JohnDoe"

It doesn't matter if you concat strings or variables. Even numbers can be concatenate.


In this examples the concatenations are calculated, however they are not used. As this is a valid expression itself it can be saved in a variable or printed directly with echo


The number of concatenations is unlimited, however php concatenate only 2 expressions together and use this result for the next concatenation.

$surname.' '.$lastname;
// surname + one space + lastname
echo 'I am '.$name.', good morning.';

It can be tricky to concatenate variables and strings if they contain single quotes and double quotes. There can be some errors if you use html code.

// you want a link <a href="index.php?section=XYZ">Link</a>, in this
// XYZ part should be filled with a variable
$var 'XYZ';
'<a href="index.php?section='.$var.'">Link</a>';   // one valid solution
echo "<a href=\"index.php?section=\".$var.\">Link</a>";
// this would generate <a href="index.php?section=".XYZ.">Link</a> as the text, which is not what you want
echo '<a href="index.php?section=".$var.">Link</a>';
// this would generate <a href="index.php?section=".$var.">Link</a>, which is also not what you want

Some may be get irritated to write something like .'" or maybe ."\" after variables. However after the concat operator you can write any string which may contain any escape sequences you want. To don't get irritated you first write the full html code and then add the variable with the concatenate operator.

echo '<a href="index.php?section=XYZ">Link</a>';
//                               ^^^
//                 replace with  '..'  (which is invalid atm.)
//                                 |
//                                 V
echo '<a href="index.php?section='..'">Link</a>';
//                                ^^
//                     insert the variable
//                                   |
//                                   V
echo '<a href="index.php?section='.$var.'">Link</a>';

With sprintf you got some possibilities to fill a string with a variables content.

Questions about the chapter

No questions

Back to Next to
Copyright © to the OPs of #php/QuakeNet Valid XHTML 1.0 Strict Valid CSS!