PHP For Beginners – Single Or Double Quotes

Overview:

There is a difference between single and double quotes when it comes to PHP. PHP handles them quite differently, as you will learn in this article.

Strings

Before you can understand the difference between using single quotes over double quotes for strings, let’s start first with an introduction to PHP Strings.

Definition: Strings are groups of characters used to represent information. They can be any combination of numbers, letters or characters.

For Example:

This is a String:
What time is it?

And so is this:
fdsaaf 3 3232 2dfs0s____+ ee#$

To represent a string in PHP, wrap it with either a pair of single or double quotes.

‘Who took the trash out at 3:32am?’ (single quotes)

“Seela said she did, but is was closer to 6:30am!” (double qoutes)

Variables

Variables are virtual containers in a program that store information for you. PHP variables start with a dollar sign $.

To have PHP remember my favorite color, type:
$myColor = ‘blue’;

Do you see what happened? The PHP variable $myColor was set equal to a String. The string ‘blue’ was wrapped inside single qoutes.

If an echo statement is placed in front of a PHP variable, the value of that variable will be output to the screen.

$myColor = ‘blue’;
echo $myColor;
?>

The output to the screen would be: blue (without the quotes).

Putting A Variable In A String

PHP gives you the ability to place one or more variables right inside a string. This is called dynamic replacement. It will take the value of the variable, and place that value inside the containing string.

For example:

// a variable called day that is set equal to Thursday
$day = ‘Thursday’;

// a variable called workPeriod set equal to a single quoted string
$workPeriod = ‘I start work on $day. ‘;
// a variable called rentalPeriod set equal to a double quoted string
$rentalPeriod = “The unit is available on $day.”;

echo $workPeriod;
echo $rentalPeriod;
?>

The Output would be:
I start work on $day. The unit is available on Thursday.

Single Versus Double Quotes

Do you see the difference above. If a PHP variable is placed inside a string that is contained with single quotes, It Won’t Be Parsed By The PHP Engine, and it won’t be replaced by the variable’s value. The string output was exactly what was typed: I start work on $day. ($day was not replaced with it’s value of Thursday).

However, if the same variable is placed inside a string with double quotes, then the variable is parsed, and it’s value is shown right in the string. The unit is available on Thursday.

Conclusion

Use single quotes around strings that do not have PHP variables inside that string.
$soupToday = ‘split pea’;

Use double quotes around strings that will contain PHP variables inside that string.

$meal = “Today they have my favorite soup, $soupToday”;