Single vs double quotes
Single '...' |
Double "..." |
|---|---|
| text exactly as written | variables are replaced |
only \' and \\ escapes |
\n, \t, \", \$ work |
| slightly faster | convenient for messages |
Joining strings
Use the dot operator .:
$full = $first . ' ' . $last;
$msg .= ' more text'; // append
Escape characters (double quotes)
\n new line, \t tab, \" quote, \$ dollar sign.
Note: \n is a new line in the source; in HTML use <br> or nl2br().
Heredoc — long text
$html = <<<HTML
<div class="card">
<h3>$title</h3>
</div>
HTML;
Works like double quotes, great for email templates and blocks of HTML.
Example
Example — Building strings
PHP
<?php
$first = 'Neha';
$last = 'Singh';
$full = $first . ' ' . $last;
$msg = "Welcome, $full!";
$msg .= ' Your course starts on Monday.';
$title = 'Certificate';
$card = <<<HTML
<div style="border:1px solid #ccc;padding:10px">
<h3>$title</h3>
<p>Awarded to $full</p>
</div>
HTML;
echo $msg . '<br>';
echo "Price: \$99<br>";
echo $card;
Output: Welcome, Neha Singh! Your course starts on Monday. / Price: $99 / a bordered box with "Certificate" and "Awarded to Neha Singh".