PASSWORD RESET

Your destination for complete Tech news

PHP

How to prepend a string in PHP?

592 0
< 1 min read

To prepend a string to the beginning of another string in PHP, you can use the concatenation operator (.).

Here is an example of how to prepend a string to the beginning of another string:

$str1 = 'Hello';
$str2 = 'World! ';

$str1 = $str2 . $str1;

echo $str1; // Outputs: "World! Hello"

In this example, the $str1 variable is initialized with the string 'Hello', and the $str2 variable is initialized with the string 'World! '. The concatenation operator (.) is then used to concatenate the $str2 string and the $str1 string, and the result is assigned back to the $str1 variable.

The concatenation operator (.) has a higher precedence than most other operators, so you may need to use parentheses if you want to concatenate strings as part of a larger expression.

For example:

$str = 'Hello' . ' World!' . ' How are you?';
echo $str; // Outputs: "Hello World! How are you?"

$str = ('Hello' . ' World!') . ' How are you?';
echo $str; // Outputs: "Hello World! How are you?"

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.