Strings in PHP
Single vs double quotes
Single quotes print text exactly, double quotes interpolate variables and read escape sequences like newline:
echo "First\nSecond"; // two lines
echo 'No \n here'; // prints \n as text
Concatenation with dot
The dot glues strings together. Surround it with spaces so the line stays readable:
$first = "Ada";
$last = "Lovelace";
$full = $first . " " . $last;
echo $full; // Ada Lovelace
Heredoc and nowdoc
Long texts read better as heredoc: an opening marker, plain lines, and the same marker at the start of the closing line. Variables still interpolate inside:
$name = "Ada";
$text = <<<TEXT
Hello, $name!
Welcome back.
TEXT;
echo $text;
Nowdoc uses the same shape with a quoted marker and never interpolates, which fits samples with dollar signs:
$sample = <<<'TEXT'
Price: $5, no variables here.
TEXT;
echo $sample;
Length and access by offset
strlen counts bytes, and square brackets read one byte by its offset starting from zero:
$word = "PHP";
var_dump(strlen($word)); // int(3)
echo $word[0]; // P
echo $word[2]; // P
For alphabets beyond ASCII use mb_strlen, because strlen counts bytes and not characters.
Next: Numbers in PHP
Автор статьи: Arthur Isaev