Why a Full Stop, "." and Not a Plus Symbol, "+", for String Concatenation in PHP

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

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.

Why is the PHP string concatenation operator a dot (.)?

I think it is a good idea to have a different operator, because dot and plus do completely different things.

What does "a string" + "another string"; actually mean, from a non specific language point of view?

Does it mean

  • Add the numerical value of the two strings, or,
  • concatenate the two strings

You would assume it is the second, but a plus sign is used for numerical addition in all cases except Strings. Why?

Also, from a loosely typed point of view (which PHP is), a php script

$myvar = 1;
$myvar2 = 2;

// would we expect a concatenation or addition?
$concat = $myvar + $myvar2;

The dot notation therefore specifies that it is clearly used for concatenation.

It is not that it is confusing, it is that it is not intuitive because all the other languages do it in a different way. And, is this a good reason to follow the trend? Doing things the way they are always done, is not always the right way.

Difference between period and comma when concatenating with echo versus return?

return only allows one expression, but echo allows a list of expressions where each expression is separated by a comma.

But note that since echo is not a function but a special language construct, wrapping the expression list in parenthesis is illegal.

What does the .= operator mean in PHP?

It's the concatenating assignment operator. It works similarly to:

$var = $var . "value";

$x .= differs from $x = $x . in that the former is in-place, but the latter re-assigns $x.

String concatenation using operator || or format() function

There are basically 4 standard tool for concatenating strings. Simplest / cheapest first:

The concatenation operator || ...

  • returns NULL if any operand is NULL. (May or may not be desirable.)
  • is a bit faster than format() or concat().
  • allows shortest syntax for very few strings to concatenate.
  • is more picky about input types as there are multiple different || operators, and the input types need to be unambiguous for operator type resolution.
  • concatenating string-types is IMMUTABLE, which allows their safe use in indexes or other places where immutable volatility is required.

concat() ...

  • does not return NULL if one argument is NULL. (May or may not be desirable.)
  • is less picky about input types as all input is coerced to text.
  • allows shortest syntax for more than a couple of strings to concatenate.
  • has only function volatility STABLE (because it takes "any" input type and coerces the input to text, and some of these conversions depend on locale of time-related settings). So not suitable where immutable volatility is required. See:
    • CONCAT used in INDEX causes ERROR: functions in index expression must be marked IMMUTABLE

concat_ws() ("with separator") ...

  • allows shortest syntax when concatenating strings with separators.
  • only inserts a separator for not-null strings, simplifying that particular (frequent) case a lot.
  • is otherwise like concat().

format() ...

  • allows for readable, short code when concatenating variables and constants.
  • provides format specifiers to safely and conveniently quote stings and identifiers (to defend against SQL injection and syntax errors), making it the first choice for dynamic SQL. (You mention trigger functions, where a lot of dynamic SQL is used.)
  • is the most sophisticated tool. You can reuse the same input multiple times (with different quotation using different format specifiers).
  • does also not return NULL if any of the input parameters are NULL. (May or may not be desirable.)
  • also has only volatility STABLE.

Further reading:

  • Combine two columns and add into one new column
  • How to concatenate columns in a Postgres SELECT?
  • Insert text with single quotes in PostgreSQL
  • SQL syntax: Concatenating multiple columns into one

HTML/PHP GET only retrieves numeric input

You're using the wrong operator for concatenation. In php, the concatenation operator is a period/dot: .

So your code should be:

echo "accId = " . $accIdd;

A plus sign + is the concatenation operator in JavaScript.

Using the + here means you're actually adding things together, not concatenating, so PHP is thinking blah + 643etc = 643.

Can you append strings to variables in PHP?

This is because PHP uses the period character . for string concatenation, not the plus character +. Therefore to append to a string you want to use the .= operator:

for ($i=1;$i<=100;$i++)
{
$selectBox .= '<option value="' . $i . '">' . $i . '</option>';
}
$selectBox .= '</select>';

What does a . (dot) do in PHP?

On its own, that does nothing at all (it's not valid syntax). However, if you have something like this:

<?php

$string1 = "Hello ";
$string2 = "world!";
$string = $string1 . $string2;

echo $string;

?>

You will see Hello world!. The . is the string concatenation operator.

Email received from PHP form shows 0 for the content

Judging by your submitted code, it looks like you're attempting to take the form submitter's name and their message and combine it into a single string that will be placed within the body of your email.

The primary issue that stands out is how you're attempting to concatenate (combine) the strings. In PHP, the concatination operation is the period ("."). With your current code, it's attempting to add the two strings like numbers, which is why you're encountering that 0 in your email body.

Let's take your current code, and apply that fix:

$content = $_POST['name'] . $_POST['message'];

Secondly, let's take a look at the actual output of your $content variable. Should I submit the name "Jon" and my message be "Hello, friends!" with your code as it is now, we would end up with:

JonHello,Friends!  

To remedy this, let's add in a colon and a space to denote that the user is saying this message:

$content = $_POST['name'] . ': ' . $_POST['message'];

Now, should we output the $content variable, we'll see:

Jon: Hello, Friends!

Bear in mind, our addition of the colon and space could be substituted for any other string.

For instance, we could modify our concatenation only slightly to add a bit of flavor to our text and have the user "say" her/his name:

$content = $_POST['name'] . 'says: "' . $_POST['message'] .'"';

This code, when output, would produce:

Jon says: "Hello, friends!"

I hope that helps, Grand. Let me know if you have any further questions.



Related Topics



Leave a reply



Submit