PHP: Single and Double QuotesLocation: Articles > PHP > Here If you have coded HTML or PHP, you may notice that you can see both single quotes (') and double quotes (") around strings such as attribute values. In HTML, there is hardly a difference and is merely a matter of preference with the double qoutes being the convention as it is the most widely used. However in PHP, have you ever wondered if there is a difference and if you haven't, you may be missing out on some of the functionality provided with the use of double quotes. Table of ContentsThe differenceIn PHP, the single quotes (') are made for quick assignment of text into a string. Nothing special and it is used for simple strings or when outputting HTML as the usage of (') in PHP allows for easy use of the (") in the HTML for attribute values. The difference with using double quotes (") is that you can have special formatting, eg. tab characters, "new line" characters and so on. Also, you can use variables directly without having to use concatenation. Obviously, this extra formatting and searching for variables leads to slower execution but this is very hard to notice as the difference in time is a tiny fraction of a second. Just a note, some readers may notice that a single quote (') can be used for the attribute values. I don't recommend this and it is better to stay consistent. The usage of double quotes (") is more widely used and accepted. Using special formattingUsing the backslash (\), you can use code that adds special characters to your text. The string "first line\nsecond line" is text seperated by a "new line", this is done with the use of \n. There are many other characters, for example: \t is a tab. Look at the PHP manual for more. Using variablesPHP variables can be directly inserted into text like in the following example: <?php
$text = 'carrot' echo "This is a $text"; // Outputs: This is a carrot ?> This can be extremely useful especially when dealing with templates where a lot of the data generated will be dependant on variables. Note that you can also use array elements however these must be enclosed in curly braces to seperate them from normal text. <?php
$text[1] = 'banana'; echo "This is a {$text[1]}"; // Outputs: This is a banana ?> The curly braces can also be used for normal variables and is useful in this situation where the output is to be 5th and 5 is the value of a variable. Why is this a problem? Well, as can be seen there is no space between the 5 and the text after so you might try echo "$numberth";. You know you want it to be $number and then th but PHP actually looks for a variable named $numberth which probably doesn't exist. Here is the solution: <?php $number = 5; echo "You are our {$number}th visitor!"; // Outputs: You are our 5th visitor! ?> |