Introduction

Creating a string variable is to assign a literal string value to a new variable name:

$myString ='hello';

Here, the string literal hello is enclosed in single quotation marks '.

You can also use double quotation marks ", as follows:

$myString = "hello";

If you enclose a string in single quotation marks, PHP uses the string exactly as typed.

Double quotation marks give you a couple of extra features:

  • Any variable names within the string are parsed and replaced with the variable's value
  • You can include special characters in the string by escaping them

Demo

<?php
$myString ='world';
echo "Hello, $myString! \n "; // Displays "Hello, world!"
echo 'Hello, $myString! \n'; // Displays "Hello, $myString!"
echo " Hi\tthere!"; // Displays "Hi      there!"
echo 'Hi\tthere!'; // Displays "Hi\tthere!"
?>//from   ww  w  .j  a  v  a  2 s  .co m

Result

Using double quotes causes the $myString variable name to be substituted with the actual value of $myString.

However, when using single quotes, the text $myString is retained in the string as-is.

With the "Hi there!" example, an escaped tab character \t is included within the string literal.

When double quotes are used, the \t is replaced with an actual tab character.

The same string enclosed in single quotes results in the \t characters being passed through intact.

Related Topic