Skip to main content
A string in PHP is implemented as an array of bytes coupled with an integer indicating the length of the buffer. Because PHP does not dictate a specific character encoding at the core language level, a “character” in a standard PHP string is strictly equivalent to a single byte. Consequently, native string functions operate on byte values rather than Unicode code points. PHP provides four syntactical methods for defining string literals: 1. Single Quoted Single quotes create literal strings. Escape sequences (other than \' and \\) and variables are not evaluated or parsed.
2. Double Quoted Double quotes instruct the PHP engine to parse the string for escape sequences (e.g., \n, \t, \x0F) and interpolate variables.
3. Heredoc Heredoc syntax behaves identically to double-quoted strings but is designed for multiline declarations without requiring escaping for internal quotes. It is initialized using <<< followed by an identifier.
4. Nowdoc Nowdoc syntax behaves identically to single-quoted strings. It is initialized using <<< followed by an identifier enclosed in single quotes. No parsing or interpolation occurs.

Variable Interpolation

When using double quotes or Heredoc syntax, PHP supports two forms of variable interpolation:
  • Simple Syntax: The parser greedily matches a dollar sign ($) followed by a valid variable name.
  • Complex (Curly Brace) Syntax: Enclosing the variable in curly braces {$...} explicitly defines the boundary of the variable name, allowing for disambiguation and the evaluation of complex expressions like array indices or object properties.

String Concatenation

PHP utilizes the dot (.) operator for string concatenation. The concatenating assignment operator (.=) appends the right-hand argument to the existing left-hand string variable, mutating it in place.

Byte Access and Mutation

Because PHP strings are zero-indexed byte arrays, individual bytes can be accessed and mutated using array offset syntax ([]).
Note: Modifying a string via byte offsets does not account for multibyte character encodings (like UTF-8). Mutating a byte within a multibyte character will result in a corrupted character payload.

Memory and Length Mechanics

The length of a string is determined by its byte count, not its character count. The native strlen() function returns the size of the internal byte array.
To accurately measure or manipulate strings containing multibyte characters, developers must utilize the mbstring extension (e.g., mb_strlen(), mb_substr()), which parses the byte array according to a specified character encoding. On 64-bit builds of PHP, the maximum length of a string is bounded only by the system’s available memory and the memory_limit directive in php.ini. On 32-bit builds, the maximum string length is strictly 2GB (2,147,483,647 bytes).
Tired of Poor PHP Skills? Fix That With Deep Grasping!Learn More