PHP - String Operators



There are two operators in PHP for working with string data types: concatenation operator (".") and the concatenation assignment operator (".="). Read this chapter to learn how these operators work in PHP.

Concatenation Operator in PHP

The dot operator (".") is PHP's concatenation operator. It joins two string operands (characters of right hand string appended to left hand string) and returns a new string.

$third = $first . $second;

Example

The following example shows how you can use the concatenation operator in PHP −

<?php
   $x="Hello";
   $y=" ";
   $z="PHP";
   $str=$x . $y . $z;
   echo $str;
?>

Output

It will produce the following output −

Hello PHP

Concatenation Assignment Operator in PHP

PHP also has the ".=" operator which can be termed as the concatenation assignment operator. It updates the string on its left by appending the characters of right hand operand.

$leftstring .= $rightstring;

Example

The following example uses the concatenation assignment operator. Two string operands are concatenated returning the updated contents of string on the left side −

<?php
   $x="Hello ";
   $y="PHP";
   $x .= $y;
   echo $x;
?>

Output

It will produce the following result −

Hello PHP

Working with Variables and Strings

In the below PHP code we will try to work with variables and strings. So you may know that you can also concatenate strings with variables in PHP. Here two variables are combined with other strings to create a sentence −

<?php
   $name = "Ankit";
   $age = 25;
   $sentence = "My name is " . $name . " and I am " . $age . " years old.";
   echo $sentence;
?> 

Output

This will generate the below output −

My name is Ankit and I am 25 years old.

Using Concatenation in Loops

Now the below code demonstrate how concatenation can be used inside loops to create a long string. See the example below −

<?php
   $result = "";
   for ($i = 1; $i <= 5; $i++) {
      $result .= "Number " . $i . "\n";
   }
   echo $result;
?> 

Output

This will create the below output −

Number 1
Number 2
Number 3
Number 4
Number 5

Combining Strings with Different Data Types

In the following example, we are showing how you can combine different data types with strings and show the output −

<?php
   $price = 100;
   $message = "The price is " . $price . " rupees.";
   echo $message;
?> 

Output

Following is the output of the above code −

The price is 100 rupees.
Advertisements