PHP Lesson 11 – Concatenation Operator and Strings

Last updated on November 27th, 2023

What is the concatenation operator?

There is another important operator in PHP – the concatenation operator. In PHP, concatenation is the process of combining or joining two or more strings together.

The concatenation operator in PHP is a period (.). It allows to combine text, variables, or values to create longer strings.

Example of using concatenation operator:

  $firstName = "John";
  $lastName = "Doe";

  // Concatenate the first name and last name to create a full name
  $fullName = $firstName . " " . $lastName;

  echo $fullName;

In this example we have two string variables, $firstName and $lastName, which store the values “John” and “Doe,” respectively. We use the concatenation operator (.) to combine these two strings along with a space ” ” to create the full name. The result of the concatenation is stored in the variable $fullName. Finally, we use echo to display the full name, which is “John Doe.”

Concatenation is a useful technique when you want to build dynamic strings by combining various pieces of text or variables. It’s commonly used for constructing messages, URLs, or any content that involves merging different text elements together.

What is string in PHP?

In PHP, a string is a data type used to store and manipulate text or sequences of characters. Strings can consist of letters, numbers, symbols, spaces, and even special characters like newline or tab. They are one of the fundamental data types in PHP and are used extensively in programming for tasks like storing names, messages, file content, and more.

Strings can be combined using the concatenation operator (.).

You can declare a string in PHP by enclosing the text within either single quotes (‘) or double quotes (“). For example:

Single quotes: $str = ‘Hello, World!’;
Double quotes: $str = “Hello, World!”;

Strings in PHP are immutable, which means once a string is created, you cannot change its characters directly. Instead, you create a new string with the desired modifications.

PHP provides a wide range of string functions for manipulating and processing strings. For example, you can use strlen() to get the length of a string, substr() to extract a portion of a string, and str_replace() to replace some characters in a string with another characters.