Strings

Overview

Strings are objects: In PHP, string is implemented as an array of bytes, and an integer indicating the length of the buffer. User data submitted from a form is received by the Web server as string data.

Creating Strings

A string literal can be specified in four different ways:
  1. single quoted
  2. double quoted
  3. heredoc syntax
  4. nowdoc syntax (since PHP 5.3.0)
Note: Unlike double-quoted and heredoc syntaxes, variables and escape sequences for special characters will *not* expand when they occur in single quoted strings. That is, no parsing is performed.

Single-Quoted Example:
//syntax:
$myStr1 = 'World!';
$myStr2 = 'Hello ' . $myStr1;
echo $myStr2;
Hello World!

Single-Quoted Example (no parsing/expansion):
$expand = 'test';
$either = 'me';

echo 'This will not parse/expand: \$50K';
echo 'Variables do not $expand $either';
This will not parse/expand: \$50K
Variables do not $expand $either

Double-Quoted Example:
If the string is enclosed in double-quotation marks ("), PHP will interpret escape sequences for some special characters:

Variable parsing:
When a string is specified in double quotation marks (or with heredoc), variables are parsed within it. (Sometimes, known as variable substitution, or interpolation.)

Double-Quoted Example:
//syntax:
$myStr1 = "World!";
$myStr2 = "Hello " . $myStr1;
echo $myStr2;
Hello World!

Double-Quoted Example (employs parsing/expansion):
$expand = "test";
$either = "me";

//both of the following double-quoted string statements will expand
echo "Both of these will parse/expand: \$50K";
echo "Variables do $expand $either";
Both of these will parse/expand: $50K
Variables do test me

Moreover, there are two types of syntax: simple, and complex. The simple syntax is the most common and convenient (as above examples). It provides a way to easily embed a variable, an array value, or an object property in a string.

The complex syntax uses curly braces {} surrounding the expression.

When a dollar sign ($) is encountered, the parser will read as many tokens as possible to form a valid variable name. To avoid parser interpretation issues, enclose variable names in curly braces {} to explicitly specify the end of the variable name.

Complex Example:
$myStr1 = "World";
$myStr2 = "Hello ${myStr1}s";
echo $myStr2;
Hello Worlds

Note: Curly brackets {} must only include the variable name w/o the dollar ($) sign.

Heredoc:
A third way to delimit strings is the heredoc syntax: <<<. After this operator, an identifier is provided, then a newline. The string itself follows, and then the same identifier again to close the quotation.

The closing identifier must begin in the first column of the line. Also, the identifier must follow the same naming rules as any other label in PHP: it must contain only alphanumeric characters and underscores, and must start with a non-digit character or underscore.

Note:
It is very important to note that the line with the closing identifier must contain no other characters, except possibly a semicolon (;). That means especially that the identifier may not be indented, and there may not be any spaces or tabs before or after the semicolon. It's also important to realize that the first character before the closing identifier must be a newline as defined by the local operating system. This is \n on UNIX systems, including Mac OS X. The closing delimiter (possibly followed by a semicolon) must also be followed by a newline.

Heredoc Example:
$language = "<strong>PHP</strong>";
$str = <<<EOD
Example of $language string
spanning multiple lines
using heredoc syntax.
EOD;

echo $str;
Example of PHP string spanning multiple lines using heredoc syntax.

Note:
Heredoc text behaves just like a double-quoted string, without the double quotes. This means that quotes in a heredoc do not need to be escaped, but the escape codes listed above can still be used. Variables are expanded, but the same care must be taken when expressing complex variables inside a heredoc as with strings.

Nowdoc:
A fourth way to delimit strings is with nowdoc. Nowdocs are to single-quoted strings what heredocs are to double-quoted strings. A nowdoc is specified similarly to a heredoc, but no parsing is done inside a nowdoc. The construct is ideal for embedding PHP code or other large blocks of text without the need for escaping.

Note:
A nowdoc is identified with the same <<< sequence used for heredocs, but the identifier which follows is enclosed in single quotes, e.g. <<<'EOT'. All the rules for heredoc identifiers also apply to nowdoc identifiers, especially those regarding the appearance of the closing identifier. (Important: nowdoc syntax will cause errors in versions of PHP less than 5.3.0.)

Nowdoc Example:
$language = "<strong>PHP</strong>";
$str = <<<'EOD'
Example of $language string
spanning multiple lines
using nowdoc syntax.
EOD;

echo $str;
Example of $language string spanning multiple lines using nowdoc syntax.

Comparisons

test10 is greater than test6

While in PHP you could possibly use the strict comparison operator (===), you should not use the loose comparision operator (==) on strings, as it can lead to incorrect evaluations, as per below.

A better solution is to use one of the various built-in string comparison functions:

strcmp() function (case-sensitive string comparison):
Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.

strcasecmp() function (case-insensitive string comparison):
Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.
//syntax:
int strcmp (string $str1 , string $str2)
//syntax:
int strcasecmp (string $str1 , string $str2)
Examples:
$myPassword = "test";
$yourPassword = "Test";

//case-sensitive comparison
if(strcmp($myPassword, $yourPassword) == 0)
{
  echo "Logged in.";
}
else
{
  echo "Please see your system administrator.";
}

//case-insensitive comparison
if(strcasecmp($myPassword, $yourPassword) == 0)
{
  echo "Logged in.";
}
else
{
  echo "Please see your system administrator.";
}
Please see your system administrator.

Logged in.

Problems with using == comparison operator:
var_dump(0 == "a"); // 0 == 0 -> true
var_dump("1" == "01"); // 1 == 1 -> true
var_dump("10" == "1e1"); // 10 == 10 -> true
var_dump(100 == "1e2"); // 100 == 100 -> true

switch ("a") 
{
case 0:
  echo "0";
  break;
case "a": // never reached because "a" is already matched with 0
  echo "a";
  break;
}

//Example 1 with '==' comparison operator
$a = 0;

if ($a == "Zero") 
{
  echo 'True';
} 
else 
{
  echo 'False';
}

//Example 2 with '===' comparison operator
$a = 0;

if ($a === "Zero") 
{
  echo 'True';
} 
else 
{
  echo 'False';
}
bool(false)
bool(true)
bool(true)
bool(true)
a
Example 1 with '==' comparison operator
False
Example 2 with '===' comparison operator
False
References:
  1. Strings
  2. Strings
  3. Details of the String Type
  4. Comparison Operators
  5. Comparing strings in PHP
  6. String conversion to numbers