PHP Strings


In PHP, strings are sequences of characters used to represent text. Strings are one of the most commonly used data types in PHP and are essential for tasks such as displaying messages, processing user input, and manipulating text data.

Basic String Syntax

Defining a String:

$string = "Hello, World!";

Types of Strings:

  1. Single-Quoted Strings:

    • Enclosed in single quotes (').
    • Variables inside single-quoted strings are not parsed.
    • Special characters like \n (newline) are treated as literals.

    Example:

    $name = 'Alice'; echo 'Hello, $name'; // Outputs: Hello, $name echo 'Line break \n here'; // Outputs: Line break \n here
  2. Double-Quoted Strings:

    • Enclosed in double quotes (").
    • Variables inside double-quoted strings are parsed and replaced with their values.
    • Special characters like \n (newline) are interpreted.

    Example:

    $name = 'Alice'; echo "Hello, $name"; // Outputs: Hello, Alice echo "Line break \n here"; // Outputs: Line break // here

String Concatenation

To combine strings, use the concatenation operator (.).

Example:

<?php $firstName = "John"; $lastName = "Doe"; $fullName = $firstName . " " . $lastName; echo $fullName; // Outputs: John Doe ?>

String Length

To find the length of a string, use the strlen() function.

Example:

<?php $string = "Hello, World!"; echo strlen($string); // Outputs: 13 ?>