Strings in PHP

In programming world, a sequence of characters enclosed together is called a string. Ideally, a string is enclosed in double quotes("") such as "String". String can also be enclosed in single quotes('') such as 'hello' but it behaves and functions in an entirely different fashion. See this example to understand this:

In the examples below I have used '\n', for your HTML out put replace that with <br> HTML tag for output in a new line.

<?php

$a = "hello";
$b = 'hello';

echo $a;
echo "
"; //Printing a new line in HTML output echo $b; ?>

The output of the above code will look like what you see below:

hello
hello

Here we assigned a string hello to $a and also $b. While assigning this to $a we used double quotes and in case of $b we used single quotes. How does it matter? See the example with slight modification:

<?php

$a = "hello\n"; //attempting multi-line output
$b = 'hello\n'; //attempting multi-line output

echo $a;
echo "
"; //Printing a new line in HTML output echo $b; ?>

The output of the above code will look like

hello
hello\n

You will notice that '\n' was not printed in the output of variable $a, but it is visible in output of the variable $b. That is because when double quotes are used, the special characters used in the strings such as '\n' (linefeed) or a '\r' (carriage return) or a '\t' (horizontal tab) are processed by the PHP compiler but when using a single quote, this does not happen. When double quotes are used, PHP will process escape sequence for special characters. We will see one more example to expand our understanding of single and double quotes.

Note: Use <br> HTML tag in for output in HTML pages and use '\n' in Text and Email for new lines.

<?php 

$drink = "Tea";
$drink_1 = "Coffee";

echo "My first preference is for $drink
"; echo 'My second preference is for $drink_1
'; echo "I like $drink_1"; ?>

The output of the above code will look like

My first preference is for Tea
My second preference is for $drink_1
I like Coffee

I hope this example was clear enough and by now you might have a better understanding of difference between using a single quotes('') and a double quote ("").

In our next section, printing strings, we will revisit the difference between using a single quote and double quote with examples and also look at printing the values of variables.

Ready? Let's go to printing strings in PHP

Further reading on strings in PHP: