PHP String Operators
In this article, I would have discussed string operators in PHP. We can use the string operator for performing some task. PHP has two sting operators, Let’s see in detail.
Two types of string operators
Concatenation Operator
- A dot (.) indicates the concatenation operator.
- It converts the LHS and RHS operands to the string format and forms a new string by combining them.
Example of Concatenation operator
<?php
echo "Thank" . "You"; // Thankyou
echo "<br/>;
ehco "Life" . "Style"; // Lifestyle
?>
- In the above code, we have printed a String “Thank” then we use the concatenation operation (.) and we have another string “you“.
- The output is returned by combining two strings “Thankyou“.
- If you give an integer there will be converted into a string and then combined.
Shorthand concatenation assignment operator
- equals sign “=” indicates shorthand concatenation, assignment operator.
- It converts the LHS and RHS operands to the string format and formats a new string by combining them and assigns the resultant sting to the left hand side variable.
Note: It is recommended to add space before and after the string operators
Example for Shorthand concatenation assignment operator
<?php
$name = "John";
echo $name; // John
$name .= " Wick"
echo $name; // John Wich
?>
- Here we have the string “john“, it is stored inside the “name” variable.
- We know that We can display value inside the “name” variable. So, we use “echo” for printing variable values.
- Now, you want to append some String to it, so we can use the “.=” sign dot with an equals sign to append any string to it.
- See the above code, we have written $name .= ” Wick”, we say take the current value of variable “name” then append to string “wick”. So the output is “john wich“