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.
<?php $a = 'Good'; $b = 'Morning'; $c = $a.$b; echo " $c "; ?>
Goodmorning
Here we take two variables $a and $b as strings. We then concatenate these strings into one string using the concatenation operator (.).
<?php $a = 'Hello'; $b = [" Good morning"," Folks"]; for($i = count($b)-1; $i >= 0;$i--) { $a .= $b[$i]; } echo " $a"; ?>
Hello Folks Good morning
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.
The concatenation operator ('.') has similar precedence to the " " and " -" operators and may produce unexpected results.
<?php $val = 5; echo "Result: " . $val + 5; ?>
5
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); ?>
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!