Difference Between Single and Double Quotes in PHP

In PHP, single quotes (' ') and double quotes (" ") are used for string literals, but they have some key differences in how they handle variables and escape sequences:

Single Quotes (' '):

  1. Literal Strings: When you use single quotes, PHP treats the string as a literal. This means that no variable parsing or escape sequences (except for \\ and \') are processed inside the string.

    $name = 'World';
    echo 'Hello, $name'; // Outputs: Hello, $name
    

    In this example, $name is not parsed as a variable but is treated as plain text.

  2. Escape Sequences: The only escape sequences recognized inside single-quoted strings are \\ (for a backslash) and \' (for a single quote).

    echo 'It\'s a beautiful day!'; // Outputs: It's a beautiful day!
    

Double Quotes (" "):

  1. Variable Parsing: In double-quoted strings, PHP parses variables within the string and replaces them with their values.

    $name = 'World';
    echo "Hello, $name"; // Outputs: Hello, World
    

    Here, $name is parsed and replaced with its value.

  2. Escape Sequences: Double-quoted strings recognize a wider range of escape sequences, including:

    • \" (for a double quote)
    • \\ (for a backslash)
    • \n (for a newline)
    • \t (for a tab)
    • \r (for a carriage return)
    • \$ (for a dollar sign)
    echo "She said, \"Hello!\""; // Outputs: She said, "Hello!"
    

Performance Considerations


Summary

Choosing between single and double quotes often depends on whether you need variable interpolation or special escape sequences within your string.