How to Prepend a String in PHP?

Prepending a string in PHP means adding additional text or characters to the beginning of an existing string.

This operation can be useful when you need to insert content at the start of a string or modify strings dynamically in your PHP applications.

In this article, we'll explore different methods to prepend a string in PHP.

1. Using the Concatenation Operator (.)

The most straightforward way to prepend a string in PHP is by using the concatenation operator (.). This operator allows you to combine two or more strings into a single string.

Here's an example of how to use . to prepend a string:

$originalString = "world!";
$prependString = "Hello, ";

$resultString = $prependString . $originalString;

echo $resultString;

Output:

Hello, world!

In this example, we concatenate the $prependString to the beginning of the $originalString using the . operator.

2. Using the .= Assignment Operator

PHP also provides the .= assignment operator, which allows you to prepend a string to an existing string variable. This operator is useful when you want to update an existing string without creating a new variable.

Here's an example:

$originalString = "world!";
$prependString = "Hello, ";

$originalString = $prependString . $originalString;

echo $originalString;

Output:

Hello, world!

In this example, the .= operator prepends the $prependString to the beginning of the $originalString, updating the value of $originalString in place.

3. Using Double Quotes (" ") for Variable Interpolation

When working with double-quoted strings (" "), you can directly interpolate variables and expressions within the string. This allows you to prepend values to a string by including them within the string itself.

Here's an example:

$originalString = "world!";
$prependString = "Hello, ";

$resultString = "$prependString$originalString";

echo $resultString;

Output:

Hello, world!

In this example, we include the variables $prependString and $originalString within the double-quoted string, and PHP automatically replaces them with their values.

4. Using Arrays and implode()

If you have an array of strings that you want to prepend to a single string, you can use the implode() function.

Here's an example:

$stringArray = ["world!", "Hello, "];

$resultString = implode("", $stringArray);

echo $resultString;

Output:

Hello, world!

In this example, we have an array of strings, and implode("", $stringArray) concatenates them into a single string.

Conclusion

Prepending a string in PHP is a fundamental operation when building dynamic content or modifying strings dynamically. Whether you prefer the concatenation operator (.), the .= assignment operator, double-quoted strings for variable interpolation, or arrays with implode(), PHP offers a variety of methods to accomplish this task. Choose the method that best suits your coding style and the complexity of your string manipulation needs.