Home > Uncategorized > Difference Between Strings in PHP Encapsulated with Single and Double Quotes

Difference Between Strings in PHP Encapsulated with Single and Double Quotes

One thing that I often see in PHP code is a lot of developers not understanding the difference between strings marked with ‘ and those marked with “.

$state = 'happy';
$string_one = 'fred'; // fred
$string_two = "fred"; // fred
$string_three = 'fred is $state'; // fred is $state
$string_four = "fred is $state"; // fred is happy
$string_five = "fred is {$state}"; // fred is happy

The quotation mark (“) tells PHP that there may be variables used in the string and that it should look out for them and swap them if found. The single apostrophe (‘) means this is just a string, variables are not identified at all. As the interpreter isn’t looking for variables it’s faster. As a programmer you should always lessen the work the interpreter or compiler has to do, particularly if it speeds up the resultant code.

My personal preference for string swapping is to always use the long-hand version and identify variables with the curly braces ({ & }). I prefer this coding style as it makes it far more obvious that I’ve got a variable stuffed in there.

Categories: Uncategorized Tags:
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: