Home > Java > javaTutorial > Concatenate two strings in PHP

Concatenate two strings in PHP

PHPz
Release: 2023-09-02 22:25:06
forward
829 people have browsed it

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 ";
?>
Copy after login

Output :

Goodmorning
Copy after login

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";
?>
Copy after login

Output:

Hello Folks Good morning
Copy after login

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;
?>
Copy after login

Output:

5
Copy after login

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);
?>
Copy after login

Output:

Result:10
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template