Home  >  Article  >  Java  >  Concatenate two strings in PHP

Concatenate two strings in PHP

PHPz
PHPzforward
2023-09-02 22:25:06803browse

Concatenate two strings in PHP

PHP offers different kinds of operators having distinctive functionalities. Operators enable us to perform arithmetic activities, string concatenation, compare values ​​and to perform boolean operations, more...In this article, we will learn string operators given by PHP. Let's first learn the types of string operators in php. There are two string operators provided by PHP.

1.Concatenation Operator ("."):

This operator combines two string values ​​and returns it as a new string.

2.Concatenating Assignment operator (".="):

This operation attaches the argument on the right side to the argument on the left side.

Let's demonstrate the utility of the above operators by following examples.

Example:

<?php
$a = &#39;Good&#39;;
$b = &#39;Morning&#39;;
$c = $a.$b;
echo " $c ";
?>

Output :

Goodmorning

Explanation:

Here we take two variables $a and $b as strings. We then concatenate these strings into one string using the concatenation operator (.).

Example:

<?php
   $a = &#39;Hello&#39;;
   $b = [" Good morning"," Folks"];
   for($i = count($b)-1; $i >= 0;$i--) {
$a .= $b[$i];
}
echo " $a";
?>

Output:

Hello Folks Good morning

Explanation:

In this example, we use the concatenation assignment operator (".=") to String values ​​are concatenated with array values. $a represents a string, and $b represents an array. We use a for loop to connect the values ​​​​of the string $a and the array $b.

Note:

The concatenation operator ('.') has similar precedence to the " " and " -" operators and may produce unexpected results.

Example:

<?php
$val = 5;
echo "Result: " . $val + 5;
?>

Output:

5

Explanation:

The above code will print out "5" instead of "Result: 10" because first The string "Result5" is created and then added to 5 to get 5. This is because the non-empty non-numeric string "Result5" will be converted to 0 and added to 5 to get 5. To print out "Result: 10", use parentheses to change the priority:

<?php
$var = 5;
echo "Result: " . ($var + 5);
?>

Output:

Result:10

The above is the detailed content of Concatenate two strings in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete