Why a full stop, "." and not a plus symbol, "+", for string concatenation in PHP?


Why did the designers of PHP decide to use a full stop / period / "." as the string concatenation operator rather than the more usual plus symbol "+" ?

Is there any advantage to it, or any reason at all? Or did they just like to? :o)

2/10/2010 12:54:56 PM

Accepted Answer

The most obvious reason would probably be that PHP inherits a lot of its syntax from Perl - and Perl uses a dot (.) for string concatenation.

But, we can delve deeper into it and figure out why this was implemented in Perl - the + operator is most commonly used for mathematical equations - it's only used for concatenation in languages in which the variable type can define the way in which the operator works (simple explanation, example is C#)

var intAddition = 1 + 2;
Console.WriteLine(intAddition); // Prints 3
var stringConcat = "1" + "2";
Console.WriteLine(stringConcat); // Prints "12"

^ As you can see, the + operator is used both for concatenation and addition in C#.

Perhaps the reasoning goes lower level and is due to the boolean algebra of logic gates - + means OR in logic gates, whereas . is used as the AND operator - which makes sense when it comes to string concatenation.

It makes sense to have two separate operators, one for concatenation and one for addition - it's just unfortunate that these two can be mixed up due to other languages.

10/8/2013 12:19:51 PM

PHP's syntax is influenced by Perl, and . is the string concatenation operator in Perl.

In a weakly typed language there are advantages to having a different string concatenation and numeric addition operators: which one you use will influence which type the language coerces the variables to.

As it happens, Perl 6 will use a tilde ~ instead of a dot . for string concatenation, because . will be used for object member access. So it seems the designers of Perl now think it was a bad choice.

Perhaps, in Perl and PHP's early, non-Object-Oriented days, it seemed like as good a choice as any. Maybe the designers of both languages never envisaged them becoming strong OO languages.

As for whether PHP will one day ditch its -> member access syntax for ., who knows?

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow