Category: PHP

Difference between single-quoted and double-quoted strings in PHP

Single quotes :

  1. Single quote is little bit faster than double quote because they do not need to be parsed and also use less memory
  2. Everything inside a single quote will be treated as plain string in php.
  3. This method is used when we want the string to be written exactly as it is.
  4. We can’t use variables inside singe quotes. If we use variables inside single quotes then it will output as it is variable name
  5. When  string is specified in single quotes PHP will not evaluate it or  interpret escape characters except single quote with backslash (‘) and  backslash(\) which has to be escaped.

$age = 10;

echo 'Hello \n  \'sample\' my age is $age';

// Hello \n 'sample' my age is $age

Copy and Try this code here

Double quote:

  1. It will display a host of escaped characters (including some regexes), and  variables in the strings will be evaluated.
  2. An important point here is  that you can use curly braces to isolate the name of the variable you want evaluated.
  3. For example let’s say you have the variable $type and you what to echo “The $types are” That will look for the variable $types. To get around this use echo “The {$type}s are” You can put the left brace before or after the dollar sign. Take a look at string parsing to see how to use array variables and such.
  4. Use double quotes in PHP to avoid having to use the period to separate code in string.

$count = 1;
echo " \n The count is $count";
//Output: The count is 1

Copy and Try this code here