Creating strings
Learn to create strings with single and double quotes and the difference between them.
Creating strings
In PHP, text is represented by a string. To create a string you wrap the text in single quotes (') or double quotes ("). Both are valid; the difference will appear in this lesson and the next ones.
$city = 'Paris'; and $city = "Paris"; give the same output. Which one you pick is mostly a style choice, but double quotes have a special power: variable interpolation.
Single or double?
In PHP, single quotes are ideal for fixed text without variables; double quotes support variable interpolation. For a label like 'Total:' you pick single quotes; for a line like "$count items" you pick double quotes.
Most of the time it is a style choice, but double quotes have the extra power of placing variables inside the string automatically. We will explore that in lesson 4. For now, feel free to use either.
Exercise Declare two string variables
Assign "Coffee" to $product using single quotes. Assign "Drinks" to $category using double quotes. Then print the product name with echo $product;.
Show example solution
First assign $product with single quotes, then $category with double quotes, then echo $product;
Example solution:
<?php
$product = 'Coffee';
$category = "Drinks";
echo $product;
Test yourself
-
Which is an INVALID string assignment?
$city = Paris;- $city = 'Paris';
- $city = Paris;
- $city = "Paris";
- $city = 'Pa' . 'ris';
Show answer
$city = Paris; — Correct. Without quotes, Paris is read as a constant and triggers an error.
-
Declare a variable with a string value
$name = ____; echo $name;Show answer
$name = 'Alex'; echo $name; -
$name = "Alex"; echo 'Hello $name'; what is the output?
$name = "Alex"; echo 'Hello $name';- Hello Alex
- Hello $name;
- Hello $name
- It errors
Show answer
Hello $name — Correct. Single quotes do not interpolate; $name is written as is.