The Analogy: The Compositor's Type Case And Composing Stick
In the composing room of a letterpress shop the compositor stands at a case of type: a shallow wooden tray divided into compartments, one for each sort. A sort is a single piece of lead with one character on its face, cast to a fixed body width. The compositor holds a composing stick, a small metal tray whose adjustable jaw has been set to the measure of the job -- twenty ems, say, for a narrow column -- and picks sorts out of the case one at a time, laying them into the stick right to left, upside down, until the line fills the measure exactly. Not approximately. Exactly, because a line that does not fill the stick will shift on the press.
What the compositor is counting is not letters. It is body widths. A comma is a thin sort, a capital M is as wide as the type size itself, and the shop's case contains ligatures -- single sorts carrying "fi" or "ffl" on one face -- because those letter pairs collide if set separately. So a line reading "affluent office" is fourteen letters to a reader and twelve sorts to the compositor, and the number that matters for whether it fits the stick is twelve. Alongside the letters sit spacing materials that carry no face at all: hair spaces, thin spaces, en quads, em quads, all of them real metal occupying real width. Asking "how long is this line" is a question about the metal in the stick, not about the language on the page.
Copy arrives at the case in two piles, and the compositor must never mix them up. Marked-up copy carries the foreman's instructions in the margin -- set the customer's name here, drop in the sale date, use the standard footer -- and those instructions are meant to be carried out rather than set. The other pile is copy to be set exactly as written, letter for letter, including the marks that look like instructions: a legal notice quoting a contract, or a proof of the shop's own price card that happens to mention "insert name here" as part of the text. Same handwriting, same paper, opposite treatment. The pile a sheet came from is the only thing that tells the compositor which it is.
The failure mode is not the one you would guess. A line an em over the measure announces itself immediately: the quoins will not tighten, the forme spills lead across the press bed, and everybody knows within a minute. The dangerous mistake is the one that measures correctly by the wrong count. A compositor who treats a two-letter ligature as two sorts, or who takes a sort from a fourteen-point case while setting twelve-point, produces a stick that locks up beautifully and reads perfectly on the galley proof, and the error only appears in the printed run when the column is a hair narrow and the type sits half a point high. That is exactly what strlen does to a product name containing an accented letter: the function counts sorts, the box is drawn from that count, and the label prints two characters short with nobody able to say why. A PHP string is a run of bytes, like a stick full of metal. It is not a run of letters.
Syntax or Core Structure
PHP gives you four ways to write a string literal, and the choice between them is the choice between the two piles of copy: do you want the marks carried out, or set as written? Single quotes and nowdoc set what you wrote. Double quotes and heredoc carry out the instructions.
<?php
declare(strict_types=1);
$cut = "sirloin";
$price = 4250;
$counter = ['name' => "Whitcomb & Sons", 'till' => 3];
echo 'single: $cut costs a lot', PHP_EOL;
echo "double: {$cut} costs {$price}p", PHP_EOL;
echo "array : {$counter['name']} on till {$counter['till']}", PHP_EOL;
echo "escape: quotes \"like this\" and a dollar \$ sign", PHP_EOL;
echo 'literal: a backslash-n is \n when single quoted', PHP_EOL;
$sql = <<<SQL
SELECT name, price
FROM cuts
WHERE name = '{$cut}'
SQL;
$notice = <<<'TXT'
Set the customer name in {$name}
exactly as written, including the braces.
TXT;
echo $sql, PHP_EOL;
echo $notice, PHP_EOL;
echo "chars : ", strlen($cut), " bytes", PHP_EOL;
Output:
single: $cut costs a lot
double: sirloin costs 4250p
array : Whitcomb & Sons on till 3
escape: quotes "like this" and a dollar $ sign
literal: a backslash-n is \n when single quoted
SELECT name, price
FROM cuts
WHERE name = 'sirloin'
Set the customer name in {$name}
exactly as written, including the braces.
chars : 7 bytes
Four things happened there that are worth naming. The single-quoted line printed $cut as three characters because single quotes process exactly two escapes, a backslash before a quote and a backslash before a backslash, and nothing else. The double-quoted lines used braces around every variable, which is optional for a plain {$cut} and mandatory for {$counter['name']} -- without braces PHP parses only the simplest expressions and an unquoted array key would be a syntax error inside the string. The heredoc's closing marker was indented four spaces, and PHP 7.3 and later strip exactly that much indentation from every line of the body, which is why the SQL keeps its internal alignment but loses the outer margin. And the nowdoc, opened with a quoted marker, treated {$name} as seven characters of ordinary text: it is the legal-notice pile.
Technical Depth: Sorts, Not Letters
The four literal forms side by side
| Form | Interpolates | Escapes processed | Use it for |
|---|---|---|---|
'single quoted' | no | only \' and \\ | any string with no variables in it, which is most of them |
"double quoted" | yes | the full list below | short strings that need one or two values dropped in |
| heredoc, bare marker | yes | the full list below | multi-line SQL, HTML, or templates that need values |
| nowdoc, quoted marker | no | none at all | multi-line text that must survive exactly as typed |
Two rules save arguments. Prefer single quotes when nothing is interpolated, not for speed -- the difference is unmeasurable in real code -- but because a reader can then tell at a glance that the line contains no hidden evaluation. And always brace your interpolations. "Hi {$user['first']}" works; "Hi $user['first']" is a parse error, and "Hi $user[first]" works by an old rule that silently treats a bare word as a string key and will confuse everyone who reads it.
Escape sequences inside double quotes and heredoc
| Escape | Produces |
|---|---|
\n | line feed, byte 0x0A |
\r | carriage return, byte 0x0D |
\t | horizontal tab, byte 0x09 |
\e | escape, byte 0x1B, the start of an ANSI colour sequence |
\v and \f | vertical tab and form feed |
\\ | one literal backslash |
\$ | a literal dollar sign, so it is not read as a variable |
\" | a literal double quote; not needed in heredoc |
\x41 | one byte from hex, here the letter A |
\101 | one byte from octal, also the letter A |
\u{1F969} | the UTF-8 byte sequence for that codepoint |
Anything else after a backslash is left alone: "\d" is a backslash followed by a d, which is why regular expressions can usually be written in double quotes and still work. Usually is not always, and it is the reason regex patterns belong in single quotes as a habit.
Bytes versus characters, and the two families of functions
A PHP string is a byte array with a length. It has no encoding attached to it, no locale, and no opinion about what those bytes mean. That is why there are two families of string functions: the core ones, which count and slice bytes, and the mb_ ones from the mbstring extension, which decode UTF-8 first and then count characters. Both are correct. Only one of them is correct for the job you have.
| Byte function | Multi-byte equivalent | What actually differs |
|---|---|---|
strlen | mb_strlen | bytes versus characters |
substr | mb_substr | a byte offset can cut a character in half |
strtoupper | mb_strtoupper | since PHP 8.2 the byte version maps only a to z |
str_pad | mb_str_pad, PHP 8.3 and later | padding counted in bytes misaligns every column |
strpos | mb_strpos | the offset returned is a byte offset |
str_split | mb_str_split | the byte version can produce invalid fragments |
ucfirst | mb_convert_case with MB_CASE_TITLE | there is no direct one-for-one replacement |
strrev | nothing in core | reversing bytes destroys multi-byte characters |
wordwrap | nothing in core | the measure is counted in bytes |
The last two rows are the uncomfortable ones. There is no multi-byte strrev and no multi-byte wordwrap in the standard library, so any layout code that has to be correct for non-English text needs mb_str_split and a hand-written loop, or the intl extension. The example that closes this lesson has exactly that flaw, deliberately.
Rather than print the strings themselves, which would only prove that your terminal has the right font, this program prints the byte count, the character count, and the hexadecimal bytes. Hex is the honest view: it is what PHP actually holds.
<?php
declare(strict_types=1);
$plain = "Pate";
$fancy = "P\u{00E2}t\u{00E9}";
$cut = "beef \u{1F969}";
foreach (['plain' => $plain, 'fancy' => $fancy, 'cut' => $cut] as $label => $s) {
printf("%-6s strlen=%d mb_strlen=%d hex=%s\n", $label, strlen($s), mb_strlen($s), bin2hex($s));
}
$padded = str_pad($fancy, 6);
printf("padded strlen=%d mb_strlen=%d\n", strlen($padded), mb_strlen($padded));
printf("upper ascii=%s mb=%s\n", bin2hex(strtoupper($fancy)), bin2hex(mb_strtoupper($fancy)));
printf("substr ascii=%s mb=%s\n", bin2hex(substr($fancy, 0, 2)), bin2hex(mb_substr($fancy, 0, 2)));
Output:
plain strlen=4 mb_strlen=4 hex=50617465
fancy strlen=6 mb_strlen=4 hex=50c3a274c3a9
cut strlen=9 mb_strlen=6 hex=6265656620f09fa5a9
padded strlen=6 mb_strlen=4
upper ascii=50c3a254c3a9 mb=50c38254c389
substr ascii=50c3 mb=50c3a2
Every line of that output is a bug waiting in somebody's codebase. The four-character word with two accents is six bytes, so str_pad($fancy, 6) did nothing at all -- the string already satisfies the byte count -- and a column built on it comes out two characters narrow. The byte strtoupper changed 74 to 54, the t, and left c3a2 and c3a9 exactly as they were, so the word is now half upper case; mb_strtoupper produced c382 and c389, the correct upper-case forms. Worst is the last line: substr($fancy, 0, 2) returned the bytes 50c3, which is the letter P followed by the first half of a two-byte character. That is not a short string. It is an invalid UTF-8 string, and it will be rejected by a JSON encoder, stored as a mangled value by a strict database, and rendered as a replacement glyph by every browser on earth.
The sprintf specifiers worth memorising
sprintf and printf are the difference between a report you can read down a column and a report you cannot. The pattern is a per-cent sign, then optional flags, width, and precision, then a conversion letter.
| Specifier | Meaning | Result |
|---|---|---|
%s | the value as a string | abc |
%d | signed decimal integer | -7 |
%05d | zero padded to width five | 00042 |
%.2f | float with exactly two decimals | 3.14 |
%8.2f | width eight, right justified | four spaces, then 3.14 |
%-8s | width eight, left justified | abc, then five spaces |
%'*8s | pad with an asterisk instead of a space | *****abc |
%+d | always print the sign | +42 |
%x and %X | hexadecimal, lower and upper case | ff and FF |
%b | binary | 1010 |
%% | one literal per-cent sign | % |
%2$s | reuse argument number two, by position | -- |
Width counts bytes, exactly like str_pad, so every alignment guarantee in that table is an alignment guarantee about ASCII only. And %d on a string argument converts rather than complaining, so sprintf("%d", "12 sheep") is 12 with no warning under any strict_types setting, because strict_types governs declared parameter types and sprintf takes mixed values.
Real World Example: The Shelf-Edge Label Printer
The butcher's counter has a small thermal printer that produces shelf-edge labels thirty-two characters wide. Every label is a box drawn with plus signs and hyphens, with the product name wrapped to the measure, the weight and the price per kilo on one line, the total right-aligned against the box edge, and the stock code padded to twelve digits and grouped in fours so a human can read it back over the phone. Every one of those requirements is a string problem, and the whole label is assembled with str_pad, wordwrap, str_split, and implode.
<?php
declare(strict_types=1);
const MEASURE = 32;
$counter = [
['sku' => 4471, 'name' => "Dry-aged sirloin steak, 21 day matured", 'perKg' => 4250, 'grams' => 640],
['sku' => 118, 'name' => "Pork shoulder, boned and rolled", 'perKg' => 895, 'grams' => 1520],
['sku' => 90312, 'name' => "Chicken thighs, free range", 'perKg' => 640, 'grams' => 900],
];
function money(int $pence): string
{
return number_format($pence / 100, 2);
}
function label(array $item, int $measure): string
{
$inner = $measure - 4;
$edge = "+" . str_repeat("-", $measure - 2) . "+";
$price = intdiv($item['perKg'] * $item['grams'], 1000);
$code = implode(" ", str_split(str_pad((string) $item['sku'], 12, "0", STR_PAD_LEFT), 4));
$out = [$edge];
foreach (explode("\n", wordwrap(strtoupper($item['name']), $inner, "\n", true)) as $part) {
$out[] = "| " . str_pad($part, $inner) . " |";
}
$out[] = "| " . str_pad("", $inner) . " |";
$out[] = "| " . str_pad($item['grams'] . " g at " . money($item['perKg']) . " per kg", $inner) . " |";
$out[] = "| " . str_pad("TOTAL", $inner - 6) . str_pad(money($price), 6, " ", STR_PAD_LEFT) . " |";
$out[] = "| " . str_pad($code, $inner) . " |";
$out[] = $edge;
return implode(PHP_EOL, $out);
}
foreach ($counter as $item) {
echo label($item, MEASURE), PHP_EOL;
}
Output:
+------------------------------+
| DRY-AGED SIRLOIN STEAK, 21 |
| DAY MATURED |
| |
| 640 g at 42.50 per kg |
| TOTAL 27.20 |
| 0000 0000 4471 |
+------------------------------+
+------------------------------+
| PORK SHOULDER, BONED AND |
| ROLLED |
| |
| 1520 g at 8.95 per kg |
| TOTAL 13.60 |
| 0000 0000 0118 |
+------------------------------+
+------------------------------+
| CHICKEN THIGHS, FREE RANGE |
| |
| 900 g at 6.40 per kg |
| TOTAL 5.76 |
| 0000 0009 0312 |
+------------------------------+
The geometry all comes out of one subtraction. $inner = $measure - 4 reserves the two characters of the left frame and the two of the right, and after that every interior line is built the same way -- a frame, a padded field, a frame -- so the box cannot go crooked on one row and straight on the next. str_pad pads on the right by default, which is what text wants, and STR_PAD_LEFT pushes the total against the right frame, which is what money wants. Even the blank separator row goes through the same call, str_pad("", $inner), rather than being a hand-typed run of spaces that somebody would eventually miscount.
wordwrap is doing more work than it looks. Its fourth argument, true, is the cut flag, and it is the difference between a label printer and a support ticket: without it, a single unbroken word longer than the measure is left intact and overflows the frame, and product names in a butcher's catalogue include things like SLOW-COOKED-BONELESS-SHOULDER. With it, the word is chopped at the measure. The wrapped result comes back as one string with newlines in it, which is why explode follows immediately -- wordwrap is a formatter, not a splitter. Notice that the sirloin needed two name rows and the chicken needed one, so the labels are different heights. That is fine for a thermal printer, which feeds line by line, and it would not be fine for a pre-cut label stock, which is a requirement nobody wrote down.
The stock code line shows the three padding and splitting functions working together. str_pad((string) $item['sku'], 12, "0", STR_PAD_LEFT) turns 4471 and 90312 into twelve-digit strings so that every code has the same shape when read back over the phone; str_split(..., 4) cuts it into three groups of four; implode(" ", ...) joins them with single spaces. The explicit (string) cast is there because str_pad declares a string parameter and strict_types=1 will not silently convert an int for you -- one of the few places where the strict-types rule shows up in ordinary formatting code.
Now the flaws, and the first one is fatal rather than cosmetic. strtoupper, str_pad and wordwrap are all byte functions, so this label printer is correct only for pure ASCII names. Add PATE DE CAMPAGNE with its accents and every row containing one comes out narrower than the frame by one column per accent; worse, wordwrap with the cut flag will happily slice a two-byte character down the middle and send an invalid UTF-8 sequence to the printer. The fix is mb_strtoupper, mb_str_pad, and a hand-written wrapper over mb_str_split, because core has no multi-byte wordwrap. Second, str_pad never truncates, so the total field is six characters wide only while the total is under a thousand pounds: money(100000) is 1,000.00, eight characters, and the frame silently grows to thirty-four columns on the most expensive item in the shop. Third, label() accepts array $item with no shape at all, so a misspelt 'gram' key produces a warning and a label reading 0 g at 42.50 per kg -- a wrong price on a shelf, which is a trading-standards matter rather than a bug report. And fourth, the rows are joined with PHP_EOL, which is a carriage return and a line feed on Windows; a device protocol needs the line ending its own manual specifies, so this belongs as a hardcoded "\n" and not as the platform's preference.
Common Mistakes
- Measuring display width with
strlen. It returns bytes, so any name with an accent, a currency symbol, or an emoji in it breaks every table, box, and fixed-width report you have built. Usemb_strlenfor character counts, and remember that even that is not display width: a wide CJK character occupies two terminal columns and onemb_strlenunit. - Interpolating without braces.
"Hi $user['name']"is a syntax error and"Hi $obj->a->b"reads only the first arrow and then stops, silently concatenating->bas text. Braces make the boundary explicit and cost nothing:"Hi {$user['name']}","Hi {$obj->a->b}". - Interpolating user data into SQL or HTML.
"SELECT * FROM users WHERE name = '{$name}'"is the textbook SQL injection, and"<p>{$comment}</p>"is the textbook stored XSS. Interpolation is for values you produced; anything that arrived from outside goes through a prepared statement placeholder orhtmlspecialcharswithENT_QUOTES. - Slicing UTF-8 with
substr.substr($s, 0, 20)on a description ending mid-character produces an invalid string that a JSON encoder will refuse and a browser will render as a black diamond.mb_substris the same call with the correct arithmetic. - Assuming
str_pador%10swill truncate. Neither ever shortens a value; they only ever lengthen it. A field that is too long silently widens the row, and the box, table, or fixed-width file you were generating is now malformed. Pair every pad with an explicitmb_substrif the value can be too long. - Using the deprecated dollar-brace form.
"${name}"and"${arr['k']}"are deprecated as of PHP 8.2 and will be removed; they also read almost identically to the correct{$name}form, which is why they survive in codebases for years. The brace goes after the dollar sign, always. - Comparing strings with
==when either one might be numeric."1e2" == "100"is true because both look like numbers and are compared as numbers, and"0x1A" == "26"is false because only one of them does. Compare strings with===, or withhash_equalswhen the comparison is a secret. - Mis-indenting a heredoc body. From PHP 7.3 the closing marker may be indented, and that indentation is stripped from every line -- but a body line indented less than the marker is a
ParseError, and mixing tabs and spaces between the marker and the body is the same error wearing a disguise. Pick one and let the formatter enforce it. - Reversing, splitting, or upper-casing a multi-byte string with the byte functions.
strrevreverses bytes, which turns every multi-byte character into rubbish;str_split($s, 1)cuts characters apart; anducfirston a word beginning with an accented letter does nothing at all. There is nomb_strrev--implode('', array_reverse(mb_str_split($s)))is the idiom.
Best Practices
- Decide once that your application is UTF-8, then act like it everywhere.
declare(strict_types=1)at the top of the file,mbstring.internal_encodingleft at UTF-8, the database column and connection inutf8mb4, and themb_family for anything that counts or slices. Half-measures are worse than either extreme because they fail only on the customers whose names have accents. - Single-quote by default, brace every interpolation. A single-quoted string is a string a reader can trust at a glance, and
{$thing}never has the ambiguity that$thingsometimes does. Both habits are free. - Use heredoc for multi-line output and nowdoc for anything literal. SQL, HTML fragments, and email bodies read far better as heredoc with the closing marker indented to match the code than as a run of concatenations, and nowdoc is the right home for templates, regex libraries, and sample text that must not be evaluated.
- Reach for
str_contains,str_starts_with, andstr_ends_with. They arrived in PHP 8 and they replace thestrpos(...) !== falseidiom that generated a decade of bugs from people writingstrpos(...)and forgetting that a match at position zero is falsy. - Format with
sprintf, not with concatenation. One format string shows the whole shape of the line, so a column width change is a one-character edit rather than an archaeology exercise, and the argument list makes it obvious when a value is missing. - Escape at the moment of output, for the destination it is going to.
htmlspecialcharsfor HTML,json_encodefor JavaScript, a placeholder for SQL,escapeshellargfor a command line. There is no such thing as a generally safe string, only a string that is safe for one context, so escaping on input and storing the escaped form is a mistake that eventually double-encodes everything. - Never build a string in a loop when
implodewill do. Collect the pieces in an array and join them once: it is shorter to read, it makes the separator explicit rather than requiring a trailing-comma trim, and it does not depend on the reader knowing how PHP's copy-on-write behaves. - Keep device and protocol line endings literal.
PHP_EOLis the right choice for output a human reads on the machine that produced it, and the wrong choice for anything with a wire format: HTTP headers need a carriage return and line feed, most printers and Unix tools need a bare line feed, and neither should change because the code moved to Windows.
Practice Exercises
- Prove the byte problem to yourself. Build a three-column table of five product names, one of which contains two accented characters written as
\u{...}escapes, aligned withstr_padto width twenty. Print the table, then printstrlenandmb_strlenfor each name. Now rewrite the padding withmb_str_padand diff the two outputs; if your PHP is older than 8.3, write the helper yourself. - Fix the label printer. Take the shelf-edge program and give it the three fixes named above: multi-byte aware casing and padding, a hard truncation so the total field can never exceed six characters, and a typed value object or named parameters in place of
array $item. Then feed it a lot priced at100000pence and a name with an accent, and confirm the box still measures thirty-two columns on every row. - Write the four literals from memory. Produce a file that prints the same sentence four times -- once from a single-quoted string, once double-quoted, once heredoc, once nowdoc -- where the sentence contains a variable name, a dollar sign, a pair of braces, and a backslash. You will get it wrong the first time; the point of the exercise is which of the four forms needed the fewest escapes.
- Build a fixed-width export. Write a function that renders a row of a bank-style fixed-width file: a twelve-character left-justified account name, an eight-digit zero-padded account number, and a ten-character right-justified amount in pence with no decimal point. Validate that the assembled line is always exactly thirty characters with an assertion, then deliberately pass a name of fifteen characters and watch the assertion earn its keep.