Saturday, September 1, 2018

Difference between Single-Quoted and Double-Quoted Strings in PHP

There are two types of quoted strings in PHP: single-quoted and double-quoted.

With a single quoted string, characters using by PHP to define a string must be escaped, like so...

$stringa = 'hello, \'friend\', how are you?'; // string: hello, 'friend', how are you?
$stringb = "\\file\\directory\\location.php"; // string: \file\directory\location.php

But you may also have a double-quoted string, which means that the content is more dynamic, like so...

$stringc = "hello, $friend"; // string: hello joe, ann, tom, etc..
$stringd = "where are all the ${type}s?" // string: where are all the friends? books? beers?

Single-quoted strings always execute much faster than double-quoted strings. But there are things in double-quoted strings that cannot be done by single-quoted strings alone. They will need concatenation, like so...

$stringe = "hello, " . $friend; // string: hello joe, ann, tom, etc..
$stringf = "where are all the " . $type . "s?"; // string: where are all the friends? books? beers?

If you are using single-quoted strings, you only get this performance boost by using apostrophes ("static strings", AKA: Single Quoted Strings), and not by using the quotes ("interpolated strings", AKA: Double-Quoted Strings).

No comments:

Post a Comment