Strings

PHP · Essentials · 10 min

Web code is mostly string handling: building HTML, parsing input, formatting output.

Single-quoted strings are literal: 'Hello $name\n' prints exactly that. Double-quoted strings interpolate variables and understand escapes like \n and \t. Use braces for anything more than a plain variable: "Hi {$user['name']}" or "{$order->total}".

For multi-line text use heredoc (<<<EOT ... EOT;), which interpolates like double quotes, or nowdoc (<<<'EOT'), which is literal. Since PHP 7.3 the closing marker may be indented, and that indentation is removed from every line.

Join strings with . and append with .=. Useful functions:

  • str_contains, str_starts_with, str_ends_with (PHP 8) for simple checks.
  • strtoupper, trim, str_replace, substr, explode, implode, str_pad.
  • sprintf('%05.2f', $x) and number_format for formatting.

PHP strings are byte arrays, not character arrays. strlen('héllo') is 6 because é takes two bytes in UTF-8. For text in human languages use the mbstring functions: mb_strlen, mb_substr, mb_strtoupper. PHP 8.4 added mb_trim and mb_ucfirst.

Strings can be indexed: $s[0] is the first byte, and $s[-1] the last.

Example

<?php
$name = 'Zoë';
$items = ['tea', 'cake'];

echo 'Hi $name', "\n";            // Hi $name
echo "Hi $name, {$items[1]}\n";   // Hi Zoë, cake

$text = <<<TXT
    Order for $name:
      - {$items[0]}
    TXT;
echo $text, "\n";   // indentation of the closing marker is stripped

echo strlen($name), " ", mb_strlen($name), "\n";  // 4 3
echo implode(', ', $items), "\n";                // tea, cake
var_dump(str_contains('hello', 'ell'));          // bool(true)
printf("%-6s|%06.2f\n", 'total', 3.14159);       // total |003.14

Remember

  • Single quotes are literal; double quotes and heredoc interpolate
  • Use {$expr} for array elements and properties inside strings
  • strlen counts bytes; use mb_* functions for characters

Watch out for

  • Using substr or strlen on UTF-8 user text and cutting a multi-byte character in half.

Check yourself

  1. What does strlen('café') return for a UTF-8 file?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: www.php.net/manual/en/language.types.string.php