How to concatenate strings in PHP?

by arnoldo.moen , in category: PHP General , 2 years ago

How to concatenate strings in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by jasen , 2 years ago

@arnoldo.moen 

In PHP, there are several ways to concatenate strings:

  1. Using the "." (dot) operator: The dot operator is used to concatenate two or more strings together. Here's an example:
1
2
3
$name = "John";
$age = 25;
echo "My name is " . $name . " and I am " . $age . " years old.";


This will output: "My name is John and I am 25 years old."

  1. Using the "." (dot) equals operator: This operator is used to concatenate a string to an existing string variable. Here's an example:
1
2
3
$name = "John";
$name .= " Smith";
echo $name;


This will output: "John Smith"

  1. Using double quotes: Double quotes can be used to concatenate strings and variables. Here's an example:
1
2
$name = "John";
echo "My name is $name.";


This will output: "My name is John."

  1. Using the sprintf function: The sprintf function is used to format strings. Here's an example:
1
2
3
4
$name = "John";
$age = 25;
$string = sprintf("My name is %s and I am %d years old.", $name, $age);
echo $string;


This will output: "My name is John and I am 25 years old."


These are some of the ways to concatenate strings in PHP.

Related Threads:

How to concatenate strings in PostgreSQL?
How to compare two strings in PHP?
How to get intersection between two strings in php?
How to concatenate fields in oracle?
How to concatenate string values in cakephp?
How to concatenate arrays from multiple documents in mongodb?