VOOZH about

URL: https://www.geeksforgeeks.org/php/how-to-append-a-string-in-php/

⇱ How to append a string in PHP ? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to append a string in PHP ?

Last Updated : 7 Aug, 2024

We have given two strings and the task is to append a string str1 with another string str2 in PHP. There is no specific function to append a string in PHP. In order to do this task, we have the this operator in PHP:

Using Concatenation assignment operator (".=")

The Concatenation assignment operator is used to append a string str1 with another string str2.

Syntax:

$x .= $y

Example :


Output
GeeksforGeeks

Using Concatenation Operator(".")

The Concatenation operator is used to append a string str1 with another string str2 by concatenation of str1 and str2.

Syntax:

$x . $y

Example :


Output
GeeksforGeeks

Using Double Quotes with Variables (Interpolation)

Using double quotes with variables (interpolation) in PHP allows you to embed variables directly within a string. PHP automatically replaces the variable with its value.

Example:


Output
Hello, world!

Using sprintf() Function

The sprintf() function in PHP can be used to format and append strings by specifying a format string that includes placeholders for variables. This method allows for more complex string manipulations and formatting.

Example:


Output
Hello, World!

Using implode() Function

The implode() function in PHP can be used to concatenate elements of an array into a single string, effectively appending multiple strings together.

Example:


Output
Hello World!

Using str_replace Function

The str_replace function in PHP can be used to replace all occurrences of a search string with a replacement string. By using a placeholder, we can effectively append one string to another.

In this approach:

  • We define a placeholder string (e.g., {append}) that will be replaced.
  • We concatenate the first string $str1 with the placeholder.
  • We use str_replace to replace the placeholder with the second string $str2.

Example:


Output
Hello, World!

Using array_merge and implode Functions

The array_merge function can be used to merge arrays, and by combining it with the implode function, we can concatenate multiple strings into a single string.

Example:


Output
Hello World!


Comment