A string is a datatype we first used in our original examples to assign values to variables. A string can be any combination of letters, numbers, or special symbols as long as consideration is given to characters that have functions in PHP. Before we consider special cases, let's first discuss the difference between the two string notations: the single and double quote. In every case where you may want to assign a string value to a variable, the value itself must begin and end with a pair of either single (' ') or double (" ") quotes.
PHP:
<?php
// This string begins and ends with single quotes
$mystring = 'single quoted string';
// This string begins and ends with double quotes
$mystring = "double quoted string";
?>
In this example, both variables would simply be assigned a value within the single or double quotes. However, when double quotes are used, PHP will first look inside the string for any references to variables that may exist. If any references are found, they are replaced with values before being assigned to the designated variable. Conversely, when dealing with single-quoted strings, PHP simply takes the string as-is and assigns it to the designated variable.
PHP:
<?php
$myint = 10; // Assign the variable myint to 10
$string_one = 'The value of myint is $myint';
$string_two = "The value of myint is $myint";
?>
Consider the above example. In the first line, we simply assign the integer value "10" to the variable $myint. Then, we assign two more variables $string_one and $string_two. These are identical except $string_one is stored using single quotes and $string_two is stored using double quotes. In this example, the values within the two strings are as follows:
- $string_one = The value of myint is $myint
- $string_two = The value of myint is 10
Notice that, when the value of $string_two is displayed, the variable $myint was replaced with the value "10". In the single-quoted string, however, the actual string $myint was stored.