PHP Strings

A. Basic Strings


$singleQuote = 'Hello World!';
$doubleQuote = "Hello World!";

$singleWithSpecialChars = 'String with \'escaped\' quotes.';
$doubleWithSpecialChars = "First line\nSecond Line with \"escaped\" quotes and other chars: \t \r \\ \$.";

$basicInterpolatedString = "String with variable $singleQuote embedded in it.";
// $basicInterpolatedString = 'String with variable Hello World! embedded in it.'

$arr = ['A', 'B', 'C'];
$advancedInterpolatedString = "String with variable {$arr[1]} embedded in it.";
// $basicInterpolatedString = 'String with variable B embedded in it.'

$nowdocString = <<<'SOME_DELIM'
    This is effectively a multiline string.
    The same rules as single quoted strings apply to nowdoc strings.
        * Note: when rendered the indentation before the ending delimiter will be removed from every line
    SOME_DELIM;

$herdocString = <<<OTHER_DELIM
    This is effectively a multiline string.
    The same rules as double quoted strings apply to heredoc strings.
    So $singleQuote variable will be embedded into this string.
        * Note: when rendered the indentation before the ending delimiter will be removed from every line
    OTHER_DELIM;

B. Extended/Special Characters


// Octal notation (ABC)
$octal = "\101\102\103";

// Hexidecimal notation (ABC)
$hexdec = "\x41\x42\x43";

// Unicode notation (ABC)
$unicode = "\u{41}\u{42}\u{43}";

C. String Access and direct manipulation


$example = 'abcdef123';

// Direct character access: prints "c"
echo $example[2];

// Negative direct character access: prints "1"
echo $example[-3];

// Modify character: prints "abcdZ123"
$example[4] = 'Z';
echo $example;

// Modify character negative index: prints "abcdZf1X3"
$example[-2] = 'X';
echo $example;

// Concatenation of strings; prints "abcABC"
echo 'abc' . 'ABC';

// Appending to strings; prints "initial-more text"
$append = 'initial';
$append .= '-more text';
echo $append;