Joining Character Strings with PHP String Operators

Joining Character Strings with PHP String Operators
There are two string operators for joining character strings in PHP; the concatenating assignment operator and the concatenation operator.

The first operator is used to add or append one character string to an existing character string. You will use the concatenating assignment operator, which is just a dot and an equal sign (.=), to connect the new character string to an existing character string. In the example below, we append the character string Home Of The Brave to the existing character string Land Of The Free.

Example 1
$patriotic_string = "Land Of The Free";

$patriotic_string .= " Home Of The Brave";

The $patriotic_string is now
Land Of The Free Home Of The Brave

The second operator is for joining two existing character strings together to form another character string. In the example below, Land Of The Free and Home Of The Brave are both assigned to the $patriotic_1 and $patriotic_2 variables. This time we will use the concatenation operator, which is just a dot (.), to join the two together as a third variable.

Example 2
$patriotic_1 = "Land Of The Free";

$patriotic_2 = "Home Of The Brave";

$patriotic_3 = $patriotic_1 . $patriotic_2;

The $patriotic_3 is
Land Of The FreeHome Of The Brave

As you can see in the example above, we are missing a space between the words Free and Home. We did not have this problem in the first example because there was an empty space in front of the word Home in the character string. But this time there is not an empty space included in the character string. In order to add that missing empty space, we will put the empty space between double quotation marks and treat this empty space as another character string. Then we will use two concatenation operators to join all three together.

Example 3
$patriotic_3 = $patriotic_1 . " " . $patriotic_2;

The $patriotic_3 is now
Land Of The Free Home Of The Brave






This site needs an editor - click to learn more!



RSS
Editor's Picks Articles
Top Ten Articles
Previous Features
Site Map





Content copyright © 2023 by Diane Cipollo. All rights reserved.
This content was written by Diane Cipollo. If you wish to use this content in any manner, you need written permission. Contact BellaOnline Administration for details.