• Tutorial List

PHP Single Quotes vs Double quotes, Escape Sequences & String Concatenation

Last updated Mar 24, 2020

PHP Single Quotes vs Double quotes

PHP single quotes can’t parse variables data but double quotes can, for that PHP Variable Interpolation only work with double-quotes.

<?php
  $first_name = "John";
  $last_name = "Doe";
  $full_name = "$first_name $last_name";

  echo "$fullname";
  echo "<br>";// line breaker
  echo '$full_name';
?>
Browser Output
John Doe
$full_name

In single quotes, only two escape sequences work and they are –

  • \' single-quote
  • \\ backslash

But, all Escape Sequences work with double-quotes. See the following Escape Sequences Section –


PHP Escape Sequences

Escape sequences are used to escape a character, during the string parsing, and It is also used to give special meaning to represent line breaks, tabs, etc.

\ The backslash is used to escape.

In the above, we have already discussed that you can only escape single quotes and backslash inside the single quotes. Here’s an example –

<?php
  //using a backslash to escaping a single quote
  echo 'Hi I\'m John Doe';

  echo '<br>';

  //using a backslash to escaping a backslash
  echo '\\ this is a backslash';

  echo '<br>';

  echo 'Hi I\\\'m John Doe';
?>
Browser Output
Hi I’m John Doe
\ this is a backslash
Hi I\’m John Doe

In the above, we have already discussed that all escape sequences work with double-quotes. Here’s an example –

<?php
  echo "\"Double Quotes\"";
  echo "<pre>\$dollar sign \nThis is new line \n\tA new line with tab Space</pre>";
?>
Browser Output
“Double Quotes”
$dollar sign
This is new line 
	A new line with tab Space

Check out – the list of Escaped characters


PHP Concatenation

You can Join two string together using PHP Concatenation or String operators.

In PHP, there are two string operators –

  • First is the concatenation operator ('.')
  • Second is the concatenating assignment operator ('.=')

Concatenation operator Example

This operator returns the concatenation of its right and left arguments.

<?php
  $x = "John";
  $y = "Doe";
  $z = $x.$y;

  echo "Hello "."world";

  echo "<br>";//line breaker
  echo $x." Doe";

  echo "<br>";//line breaker
  echo $x.$y;

  echo "<br>";//line breaker
  // adding space
  echo $x." ".$y;

  echo "<br>";//line breaker
  echo $z;
?>
Browser Output
Hello world
John Doe
JohnDoe
John Doe
JohnDoe

Concatenating assignment operator Example

This assignment operator appends the argument on the right side to the argument on the left side.

<?php
  $x = "John";
  $y = " Doe";

  $x .= $y;

  echo $x;
?>
Browser Output
John Doe