' and " quotes

Introduction

In PHP both ' and " can be used to define strings.
When using single quote (') to define a string, you can use " inside the string.
When using double quote (") to define a string, you can use ' inside the string.

Double quote (") would handle variables inside the string.
echo "Hello $name\n";
The output would be Hello John if $name = "John".
A line break (not shown in browser) is added with \n.

Single quote (') would not handle variables and special characters inside the string.
echo 'Hello $name\n';
The output would be Hello $name\n.

When single quote is needed in the string, you can use double quote to define the string.
echo "Hello 'John'\n";

or vice versa.
echo 'Hello "John"\n';

Code - Differences between ' and "


<?php
	$name = "John";
	echo "Hello $name\n";          // Hello John
	echo 'Hello $name\n';          // Hello $name\n

	$var = 10;
	echo "Value of var is $var\n";          // Value of var is 10
	echo 'Value of var is $var\n';          // Value of var is $var\n
?>
	

Code - When does . (concatenation) need to be used

As shown in the code below, when using ' to define a string, you need to use . (concatenation) to add variables to the string.
When using " to define a string, you do not need to use . (concatenation) to add variables to the string because PHP would handle variables inside the string.

<?php
	$name = "John";
	echo 'Hello ' . $name . "\n";          // Hello John
	echo 'Hello $name \n';                 // Hello $name \n
	echo "Hello  $name \n";                // Hello John

	$var = 10;
	echo 'Value of var is ' . $var . "\n";          // Value of var is 10
	echo 'Value of var is  $var \n';                // Value of var is $var \n
	echo "Value of var is  $var \n";                // Value of var is 10
?>
	

Task

Declare the following variables:
$firstName = "John";
$lastName = "Doe";
$age = 25;
$city = "New York";

1. Use ONLY single quote (') to echo the following:
Hello John Doe, you are 25 years old and you live in New York.

2. Use ONLY double quote (") to echo the following:
Hello John Doe, you are 25 years old and you live in New York.

Tips

Single quote (') is more convenient to use when you want to display special characters inside the string.
Double quote (") is more convenient to use when you have variables inside the string.

And as double quote has to handle variables, in theory it is slower than single quote.

Reference

PHP Strings