Zend PHP 7 Certification – Strings – Quoting

This post covers the Quoting section of the Strings chapter when studying for the Zend PHP 7 Certification.

A string literal can be specified in different ways.

  • Single quoted
  • Double quoted
  • HEREDOC/NOWDOC, which can be seen here

Single quoted strings will display things almost completely “as is.” Variables and most escape sequences will not be interpreted. The exception is that to display a literal single quote, you can escape it with a back slash, \, and to display a back slash, you can escape it with another backslash \\.

<?php

$str = 'dollars';
echo 'This costs a lot of $str.'; // This costs a lot of $str.

A backslash example can be seen below.

<?php

echo 'I'll be back'; // Error
echo 'I\'ll be back'; Outputs: I'll be back

Other examples include the following:

// Outputs: You deleted C:\*.*?
echo 'You deleted C:\\*.*?';

// Outputs: You deleted C:\*.*?
echo 'You deleted C:\*.*?';

// Outputs: This will not expand: \n a newline
echo 'This will not expand: \n a newline';

Double quote strings will display a host of escaped characters and variables in the strings will be evaluated.

If you have a variable, $type, and you what to echo out echo "The $types are", that will look for the variable $types.

You could get around this by using echo "The {$type}s are". You can put the left brace before or after the dollar sign.

This is one of the most important features about double quotes – that variable names will be expanded.

<?php

$s = "dollars";
echo "This costs a lot of $s."; // This costs a lot of dollars.

Similar to single quoted, backslashes are used to escape double quotes.

echo "John said \"Hello\""; // Outputs: John said "Hello"

Within double quotes, we can also interpret more escape sequences for special characters.

Zend PHP 7 Certification

A lot of people ask if using single quotes are faster than double quotes in terms of speed. I would not put too much weight on single quotes being faster than double quotes. There’s only really negligible differences between the two. Some speed tests of quotes and other PHP syntax can be seen at http://www.phpbench.com/.

View the other sections:

Note: This article is based on PHP version 7.1.