Open In App

How to Concatenate Strings in PHP ?

Last Updated : 09 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In PHP, strings can be concatenated using the( . operator). Simply place the ” . " between the strings you wish to concatenate, and PHP will merge them into a single string.

Using (.operator)

In PHP, the dot (.) operator is used for string concatenation. By placing the dot between strings and variables, they can be combined into a single string. This method provides a concise and efficient way to merge string elements.

Syntax

$string1 = "Hello";
$string2 = "world!";
$concatenatedString = $string1 . " " . $string2;

// Result: "Hello world!"

Alternatively, you can also use the .= operator to append one string to another, like so:

$string1 .= " world!";
// Result: "Hello world!"

Using sprintf() Function

PHP’s sprintf() function allows for formatted string construction by replacing placeholders with corresponding values. It offers a structured approach to string concatenation, particularly useful for complex string compositions.

Syntax

$name = "geeksforgeeks";
$age = 30;
$formattedString = sprintf("My name is %s and I am %d years old.", $name, $age);
echo $formattedString;

// Result: My name is geeksforgeeks and I am 30 years old.

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads