Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
PHP String Data Type
In PHP, a string data type is a sequence of characters that can contain any character from the ASCII set. Strings are one of the most commonly used data types in PHP for storing and manipulating text data.
PHP provides four different ways to define strings − single quotes, double quotes, heredoc syntax, and nowdoc syntax. Each method has its own characteristics and use cases.
Syntax
// Single quotes $var = 'Hello World'; // Double quotes $var = "Hello World"; // Heredoc $var = <<< IDENTIFIER Hello World IDENTIFIER; // Nowdoc $var = <<< 'IDENTIFIER' Hello World IDENTIFIER;
Single Quoted Strings
Single quoted strings treat most characters literally. Only the single quote and backslash need to be escaped ?
<?php $var = 'Hello World.<br> Welcome to Tutorialspoint'; echo $var; ?>
Hello World.<br> Welcome to Tutorialspoint
Double Quoted Strings
Double quoted strings parse escape sequences and allow variable interpolation ?
<?php $var = "Hello World.<br> Welcome to Tutorialspoint"; echo $var; ?>
Hello World. Welcome to Tutorialspoint
Escape Sequences
Double quoted strings recognize the following escape sequences ?
| Sequence | Meaning |
|---|---|
| Newline | |
| \r | Carriage return |
| \t | Horizontal tab |
| \ | Backslash |
| \$ | Dollar sign |
| " | Double quote |
Heredoc Syntax
Heredoc allows multiline strings with variable interpolation. The identifier must start and end on its own line ?
<?php $name = "Mahesh"; $var = <<< STR Hello $name Welcome to Tutorialspoint STR; echo $var; ?>
Hello Mahesh Welcome to Tutorialspoint
Nowdoc Syntax
Nowdoc is similar to heredoc but treats content literally like single quotes. The identifier is enclosed in single quotes ?
<?php $name = "Mahesh"; $var = <<<'STR' Hello $name Welcome to Tutorialspoint STR; echo $var; ?>
Hello $name Welcome to Tutorialspoint
Conclusion
PHP strings offer flexible options for text handling. Use single quotes for literal strings, double quotes when you need escape sequences or variable interpolation, and heredoc/nowdoc for multiline content.
