PHP Strings
Strings are sequences of characters used to store and manipulate text. PHP offers multiple ways to create strings, each with its own features and use cases. Let's explore them all!
String Syntax Options
PHP provides four ways to create strings:
| Type | Syntax | Variables Parsed? | Escape Sequences? |
|---|---|---|---|
| Single quotes | 'text' |
❌ No | Limited |
| Double quotes | "text" |
✅ Yes | ✅ Yes |
| Heredoc | <<<EOT |
✅ Yes | ✅ Yes |
| Nowdoc | <<<'EOT' |
❌ No | ❌ No |
Click Run to execute your code
Single Quotes
Single quotes create literal strings - what you see is what you get:
<?php
$name = 'John';
echo 'Hello, $name'; // Output: Hello, $name (not parsed!)
echo 'Line 1\nLine 2'; // Output: Line 1\nLine 2 (no newline!)
// Only these escape sequences work:
echo 'It\'s working'; // \' for single quote
echo 'C:\\path\\file'; // \\ for backslash
?>
Double Quotes
Double quotes parse variables and escape sequences:
<?php
$name = "John";
$age = 25;
echo "Hello, $name!"; // Output: Hello, John!
echo "Age: $age"; // Output: Age: 25
// Escape sequences work
echo "Line 1\nLine 2"; // Actual newline
echo "Tab\there"; // Actual tab
echo "Quote: \"Hi\""; // Escaped quotes
?>
Common Escape Sequences
| Sequence | Meaning | Example |
|---|---|---|
\n |
Newline | "Line 1\nLine 2" |
\r |
Carriage return | "Text\r" |
\t |
Tab | "Name\tAge" |
\" |
Double quote | "Say \"Hi\"" |
\\ |
Backslash | "C:\\path" |
$ |
Dollar sign | "Price: $10" |
Variable Interpolation
Double quotes can embed variables directly:
<?php
$name = "John";
$age = 25;
// Simple variable
echo "Name: $name";
// Array element
$user = ["name" => "Jane"];
echo "Name: {$user['name']}"; // Curly braces needed
// Object property
$person = new stdClass();
$person->name = "Bob";
echo "Name: {$person->name}"; // Curly braces needed
// Complex expressions need curly braces
echo "Next year: {$age + 1}";
?>
{$var} for complex
expressions, array elements, or object properties to avoid parsing errors!
String Concatenation
Join strings using the dot operator (.):
<?php
$first = "Hello";
$last = "World";
// Concatenation
$combined = $first . " " . $last;
echo $combined; // Output: Hello World
// Concatenation assignment
$message = "Hello";
$message .= " World"; // Same as: $message = $message . " World"
echo $message; // Output: Hello World
// Multiple concatenations
$full = "My name is " . $first . " " . $last . "!";
?>
Heredoc Syntax
Heredoc is perfect for multi-line strings with variable parsing:
<?php
$name = "John";
$age = 25;
$text = <<<EOT
Hello, $name!
You are $age years old.
This is a multi-line string.
No need to escape "quotes" or 'quotes'.
EOT;
echo $text;
?>
- Start with
<<<IDENTIFIER - End with
IDENTIFIER;on its own line - Closing identifier must have no indentation (PHP < 7.3)
- Variables are parsed like double quotes
- No need to escape quotes
Nowdoc Syntax
Nowdoc is like heredoc but doesn't parse variables (like single quotes):
<?php
$name = "John";
$text = <<<'EOT'
Hello, $name!
This $name will NOT be parsed.
Perfect for code examples or templates.
EOT;
echo $text; // Output: Hello, $name! (literal)
?>
String Access by Character
Access individual characters using array-like syntax:
<?php
$str = "Hello";
echo $str[0]; // Output: H
echo $str[1]; // Output: e
echo $str[-1]; // Output: o (last character, PHP 7.1+)
// Modify characters
$str[0] = 'J';
echo $str; // Output: Jello
?>
Common Mistakes
1. Forgetting curly braces for arrays
<?php
$user = ["name" => "John"];
echo "Name: $user['name']"; // ❌ Parse error!
echo "Name: {$user['name']}"; // ✅ Correct
?>
2. Mixing quote types
<?php
$text = "Hello'; // ❌ Syntax error!
$text = "Hello"; // ✅ Correct
?>
3. Heredoc indentation (PHP < 7.3)
<?php
$text = <<<EOT
Hello
EOT; // ❌ Parse error in PHP < 7.3 (indented)
$text = <<<EOT
Hello
EOT; // ✅ Correct (no indentation)
?>
Exercise: String Manipulation
Task: Create a formatted email template using strings!
Requirements:
- Use variables for: recipient name, product name, price
- Create a multi-line email using heredoc
- Include variable interpolation
- Format the price with a dollar sign
Show Solution
<?php
$recipientName = "Jane Smith";
$productName = "Premium Membership";
$price = 99.99;
$email = <<<EMAIL
Dear $recipientName,
Thank you for your interest in $productName!
Price: $$price
Special offer: Save 20% today!
Best regards,
The Team
EMAIL;
echo $email;
?>
Summary
- Single Quotes: Literal strings, no variable parsing
- Double Quotes: Parse variables and escape sequences
- Heredoc: Multi-line with variable parsing
- Nowdoc: Multi-line without variable parsing
- Concatenation: Use dot operator
. - Interpolation:
"Hello $name" - Complex vars: Use curly braces
{$arr['key']} - Character access:
$str[0]
What's Next?
Now that you know how to create and work with strings, let's explore String Functions - PHP's powerful built-in functions for manipulating, searching, and transforming strings!
Enjoying these tutorials?