PHP Strings - W3Schools

PHP Strings ❮ Previous Next ❯

PHP Strings

A string is a sequence of characters, like "Hello world!".

In PHP, strings are surrounded by either double quotes, or single quotes.

Example

echo "Hello"; echo 'Hello'; Try it Yourself »

Note: There is a difference between double quotes and single quotes in PHP.

Double or Single Quotes?

You can use double or single quotes, but you should be aware of the differences between the two.

A double quoted string will substitute the value of variables, and accepts many special characters, like \n, \r, \t by escaping them.

Example

A double quoted string will substitute the value of variables:

$x = "John"; echo "Hello $x"; // Returns Hello John Try it Yourself »

A single quoted string does not substitute the value of variables, and will output the string as it was written:

Example

A single quoted string outputs the string as it is:

$x = "John"; echo 'Hello $x'; // Returns Hello $x Try it Yourself »

Differences between Single and Double Quotes

Feature Single Quotes Double Quotes
Variable interpolation No - variables like $x are output literally Yes - variables are replaced with their values
Escape sequences Only \' and \\ are supported Supports many, like: \n, \t, \r, \$, \"
Performance Slightly faster (PHP does not need to parse the content) Slightly slower (PHP must scan for variables and escape sequences)
Readability Cleaner for simple, constant strings More readable for strings with many variables (do not need to use the concatenation operator (.))

Example

See some differences beween double and single quotes:

// Using double quotes $x = "John"; echo "Hello $x\n"; echo "\tHow are you?\n"; // Using single quotes $x = 'John'; echo 'Hello $x\n'; echo '\tHow are you?\n'; Try it Yourself »

Complete PHP String Reference

For a complete reference of all string functions, go to our complete PHP String Reference.

❮ Previous Next ❯ +1 Sign in to track progress

Tag » What Is A String In Php