String is a series of characters. We can wrap a string in single quotes or double quotes.
$x = "Hello"; echo $x; // Hello
However, we can only use variables in double-quote, not single-quote.
$firstName = "Dev"; echo 'Hello $firstName'; // Hello $firstName echo "Hello $firstName"; // Hello Dev
In PHP, we can join strings together using dot
$x = "Hello"; $y = "World"; $c = $x." ".$y;
We can use the backslash
\ as an “escape” character.
\n doesn’t work inside of a single-quoted string.
echo "Hello. \"This string's in double quotes.\" "; // Hello. "This string's in double quotes."
We can use a zero-based index to access a letter in a string.
The first letter is in a 0 position. A minus position is counted from the end of a string.
$x = "Hello World"; echo $x; // e echo $x[-3]; // r
We can also change a letter in a string by using bracket the same way.
$x = "Hello World"; $x = "y"; echo $x; // Helly World
We can use also use heredoc and nowdoc to declare a string.
They help improving the readability of the code.
PHP heredoc strings are like double-quoted strings, without the double-quotes. So they don’t need to escape quotes and expand variables.
We can start with the
<<< operator and an identifier.
$str = <<<TEXT a string can span multiple lines and include single quote ' and double quotes " TEXT;
<?php $x = "a"; $y = "b"; $z = "c"; echo <<<TEXT Line 1 $x Line 2 $y Line 3 $z TEXT; // Line 1 a Line 2 b Line 3 c
nowdoc is similar to single-quoted string, so we can’t use variables inside nowdoc.
<?php $name = "Dev"; echo <<<'TEXT' My name is "$name". I am going $a->b. TEXT; // My name is "$name". I am going $a->b.