0
0
PhpHow-ToBeginner · 3 min read

How to Create String in PHP: Syntax and Examples

In PHP, you create a string by enclosing text in single quotes ('') or double quotes (""). You can also use heredoc syntax for multi-line strings or complex content.
📐

Syntax

Strings in PHP can be created using single quotes, double quotes, or heredoc syntax.

  • Single quotes (''): Treat content literally, no variable parsing.
  • Double quotes (""): Parse variables and special characters like \n.
  • Heredoc: For multi-line strings and complex content, behaves like double quotes.
php
<?php
// Single quoted string
$string1 = 'Hello, world!';

// Double quoted string
$string2 = "Hello, $string1!\n";

// Heredoc string
$string3 = <<<EOD
This is a heredoc string.
It can span multiple lines.
EOD;
💻

Example

This example shows how to create strings using single quotes, double quotes with variable parsing, and heredoc syntax.

php
<?php
$name = 'Alice';

// Single quotes: variables are not parsed
$greeting1 = 'Hello, $name!';

// Double quotes: variables are parsed
$greeting2 = "Hello, $name!";

// Heredoc: multi-line string with variable parsing
$greeting3 = <<<TEXT
Hi, $name!
Welcome to PHP string creation.
TEXT;

// Output all greetings
echo $greeting1 . "\n";
echo $greeting2 . "\n";
echo $greeting3 . "\n";
Output
Hello, $name! Hello, Alice! Hi, Alice! Welcome to PHP string creation.
⚠️

Common Pitfalls

Common mistakes when creating strings in PHP include:

  • Using single quotes when you want variables to be replaced inside the string.
  • Forgetting to escape special characters inside single or double quotes.
  • Not ending heredoc syntax properly.
php
<?php
// Wrong: variable won't be replaced
$name = 'Bob';
echo 'Hello, $name!'; // Outputs: Hello, $name!

// Right: use double quotes for variable parsing
echo "Hello, $name!"; // Outputs: Hello, Bob!

// Wrong: missing semicolon after heredoc
/*
$heredoc = <<<END
This is a heredoc string
END
*/

// Right:
$heredoc = <<<END
This is a heredoc string
END;
Output
Hello, $name! Hello, Bob!
📊

Quick Reference

Summary of string creation methods in PHP:

MethodSyntax ExampleVariable ParsingUse Case
Single quotes'Hello, world!'NoSimple literal strings
Double quotes"Hello, $name!"YesStrings with variables or special chars
Heredoc<<YesMulti-line or complex strings

Key Takeaways

Use single quotes for simple strings without variable parsing.
Use double quotes to include variables and special characters inside strings.
Heredoc syntax is useful for multi-line strings with variable parsing.
Always close heredoc syntax with a semicolon on a new line.
Remember to escape special characters when needed.