String operators
. joins two values into one string. .= adds a value to the end of a string variable.
. and .=
. joins two strings into one, and .= adds a string to the end of a variable. Both convert each side to a string first, so "Order " . 1042 gives Order 1042 without a cast.
Every number can be converted this way. true gives 1, and false and null give an empty string. An object can be joined when its class implements Stringable, and the result of that method is used.
Four things cannot be converted to a string, and joining one does not compile: a bytes value, an array, an enum case, and a call that returns nothing. For the first three, the error message says what to write instead. For example, you choose the encoding of a bytes value or the fields of an array yourself.
A string in double quotes inserts values in the same way: "Hello $name" and "{$order->total}".
The examples below show strings and numbers joined into one message, a line built piece by piece with .=, and the confirmation text for an order.
Joining text and numbers into one message
<?nvs// Shows how to join text and numbers with `.`. Every value gets its text form// first, so no cast is needed, and the result is always a `string`.
string $customer = 'Ada';uint $order = 1042;decimal $total = 19.99;
// This prints: Order 1042 for Ada came to 19.99 EURecho 'Order ' . $order . ' for ' . $customer . ' came to ' . $total . ' EUR', "\n";
// A double-quoted text fills the values in where they stand, which reads// better than a long chain of joins. This prints the same line.echo "Order $order for $customer came to $total EUR", "\n";
// Use braces when the value is more than a plain variable.array<string> $items = ['desk lamp', 'cable'];// This prints: First item: desk lampecho "First item: {$items[0]}", "\n";
// `true` joins as 1, while `false` and `null` join as nothing at all. This// prints: [1] [] []bool $paid = true;bool $shipped = false;?string $note = null;echo '[' . $paid . '] [' . $shipped . '] [' . $note . ']', "\n";Order 1042 for Ada came to 19.99 EUROrder 1042 for Ada came to 19.99 EURFirst item: desk lamp[1] [] []Growing a line a piece at a time
<?nvs// Shows how to build up text one piece at a time with `.=`. It adds to the// end of the text already in the variable. That is what a loop needs when// the number of pieces is only known while the program runs.
array<string> $tags = ['urgent', 'billing', 'eu'];
string $line = '';foreach ($tags as string $tag) { // The separator goes in front of every piece but the first. An empty // `$line` is how you know this is the first one. if ($line != '') { $line .= ', '; } $line .= $tag;}// This prints: urgent, billing, euecho $line, "\n";
// The piece added does not have to be text. A number, a `bool` and `null` all// get their text form first, exactly as `.` gives them.string $status = 'retries=';$status .= 3;$status .= ' done=';$status .= true;// This prints: retries=3 done=1echo $status, "\n";
// `Core\Str::join` does the whole loop above in one call when all the pieces// are already in an array. This prints: urgent, billing, euecho Core\Str::join($tags, ', '), "\n";urgent, billing, euretries=3 done=1urgent, billing, euRendering the confirmation an order sends out
<?nvs// Shows the job `.` and `.=` do most often at work: turning records into the// text a customer reads. A class that implements `Stringable` joins in as// whatever its `toString` returns. An amount is then formatted in one place,// and every line that mentions it comes out the same.
class Money implements Stringable{ public function constructor(public decimal $amount, public string $currency) {}
public function toString(): string { return $this->amount . ' ' . $this->currency; }}
class Line{ public function constructor( public string $item, public uint $quantity, public Money $price, ) {}}
class Confirmation{ public function constructor(public string $customer, public array<Line> $lines) {}
// The subject is one join. Nothing here is cast: the number and the // object both have a text form already. public function subject(): string { return 'Your order, ' . $this->customer . ' (' . Core\Arr::count($this->lines) . ' items)'; }
// The body grows a piece at a time, because how many lines there are is // only known while this runs. public function body(): string { string $body = "Hello $this->customer,\n\n"; foreach ($this->lines as Line $line) { $body .= ' ' . $line->quantity . ' x ' . $line->item . ' at ' . $line->price . "\n"; } $body .= "\nThank you."; return $body; }}
Confirmation $mail = new Confirmation('Ada', [ new Line('desk lamp', 2, new Money(19.99, 'EUR')), new Line('cable', 1, new Money(4.50, 'EUR')),]);
// This prints: Your order, Ada (2 items)echo $mail->subject(), "\n";
// This prints the greeting, one line per item, and the closing line.echo $mail->body(), "\n";Your order, Ada (2 items)Hello Ada,
2 x desk lamp at 19.99 EUR 1 x cable at 4.50 EUR
Thank you.Details
Each value that cannot be joined has its own error:
- a
bytesvalue, an array, an enum case or a call that returnsvoidis the errorE0707. Write$data as stringforbytes,Core\Json::encode($list)for an array and$case as intfor an enum case. - an object whose class does not implement
Stringableis the errorE0412. - a
Core\Html\Markupvalue is the errorE0710. Join two of them with+, which gives a newMarkup.
A mixed value is converted when the program runs. A mixed number joins like a number. A mixed array throws a RuntimeError with the message "cannot convert an array to string".
+ on two strings is the error E0716. +, -, * and / run before ., so "n=" . $n + 1 with $n equal to 2 gives n=3.
A float loses its .0 when it is joined: 10.0 gives 10. A decimal keeps every digit it has, so 4.50 gives 4.50. A uint gives all its digits, up to 18446744073709551615.
.= writes a string, so the variable must be able to contain one. $n .= "x" on an int is the error E0401. On a ?string that is null, .= starts from an empty string.
When one side is tainted or secret, the result is tainted or secret too. $s .= $input on a plain string $s is the error E0401 when $input is tainted. echo of a joined secret value is the error E0790.
Use this when you build a string from many values
Section titled “Use this when you build a string from many values”A double-quoted string can contain variables. "Hello $name" and "Hello {$user->name}" are
often easier to read than many . operators. Strings and interpolation
shows all the ways to write a string.
Do and don’t
Section titled “Do and don’t”- Do use interpolation for short messages with a few values.
- Do use
.=to build a string in a loop. - Don’t use
+to join strings.+works on numbers only. - Don’t use
.to build HTML. Use anhtmltemplate. It escapes each value for you.
