PHP string is a list of characters that are located between single or double quotes. The max of characters should not be over 256 characters. PHP does not support the native Unicode. The string can be double-quotes or single-quotes.

In this tutorial, you will learn how to use all types of PHP strings.

Anyway, the PHP supports four types in a string.

PHP String

PHP String with Single Quoted

Single quoted starts with an inverted comma ‘ at the beginning of the string and should be ended with another one. Between them is a set of the chars list.

In the following code, we need to print welcome text with PHP using the single-quoted.

<?php 
   $value = 'Welcome to PHP Scripting Language';
?>

Note: if the string has a value contains one slash such as C:\ it would be written with a double slash C:\\.

<?php 
   echo 'File C://'; // File C:/
?> 

Also, there are no executed Escaped characters in the single-quoted

<?php 
   // This line will not \n break into the next line
   echo 'This line will not \n break into the next line'; 
?>

Another thing, you will not able to include the variable with single quotes.

<?php
   $var = 'data';
   echo 'this $var is lost'; // this $var is lost
?>

PHP String with Double Quoted

Double quoted starts with twice inverted commas” at the beginning of the string and ended with another two inverted commas. Between them is a set the characters list.

Here you will be able to pass a variable inside the double-quoted

<?php 
   $var = "data";
   echo "this $var is lost'; // this data is lost"
?>

Also, you can use the escaped characters like \n, \t, \v and you can find some others here.

<?php 
  // This line will
  // break into the next line
  echo "This line will \n break into the next line"; 
?>

Heredoc Syntax

Usually, the heredoc syntax started with “<<<” followed by the identifier as an open tag. And then it should be closed with the same identifier name

<?php
   echo <<<IDENTIFIER
   Hello world
   IDENTIFIER;
?>

The string content of this syntax should be in the new line or in the middle of syntaxes opening and closing identifiers. Also, no indentation is needed before the string. otherwise, it will show you an error.

The identifier name can contain any name you like, but it should have the same name in the closing. The Invalid indentation error is happening on PHP 7.3 and prior.

Nowdoc Syntax

In nowdoc syntax, the identifier would contain a single-quoted with no indentation or a string in the same line of the identifier.

<?php
   echo <<<'EOUT'
   Hello world
   EOUT;
?>

In the following sections, there are some examples using the PHP string.

Conclusion

In this tutorial, you understood how to use all types of strings such as single-quoted, double-quoted, heredoc and nowdoc.

In PHP data Types tutorial you will learn more data types in PHP.