Named arguments and match expressions (PHP 8.0 and later)
Named arguments let you skip optional parameters, and match compares strictly and returns a value. This runs on every version in the menu. Switch the output panel to Raw Output so the PHP_EOL line breaks are kept. Expected output: USD 1,234.50, then 1.234,50 €, USD 99 and ¥1,235.
<?php
function price(float $amount, string $currency = 'USD', int $decimals = 2): string
{
return match ($currency) {
'EUR' => number_format($amount, $decimals, ',', '.') . ' €',
'JPY' => '¥' . number_format($amount),
default => $currency . ' ' . number_format($amount, $decimals),
};
}
echo price(1234.5), PHP_EOL;
echo price(1234.5, currency: 'EUR'), PHP_EOL;
echo price(amount: 99, decimals: 0), PHP_EOL;
echo price(1234.5, 'JPY'), PHP_EOL;
Enums and readonly properties (PHP 8.1 and later)
A good way to see version switching at work. On PHP 8.1 or newer this prints "Hello PHP: Published" and then "Error: Cannot modify readonly property Post::$title". Select PHP 8.0 and run it again: the enum keyword is not recognised there, so you get a parse error instead.
<?php
enum Status: string
{
case Draft = 'draft';
case Published = 'published';
public function label(): string
{
return ucfirst($this->value);
}
}
final class Post
{
public function __construct(
public readonly string $title,
public readonly Status $status = Status::Draft,
) {}
}
$post = new Post('Hello PHP', Status::from('published'));
echo $post->title, ': ', $post->status->label(), PHP_EOL;
try {
$post->title = 'Changed';
} catch (Error $e) {
echo get_class($e), ': ', $e->getMessage(), PHP_EOL;
}
Filtering and summing arrays with arrow functions
Typical data-shaping code: array_filter with an arrow function, array_column to pull one field, and json_encode for the result. The first line prints the exact PHP_VERSION of the build you picked, which is handy when you share a link and want the reader to know what produced the output.
<?php
echo 'Running PHP ', PHP_VERSION, PHP_EOL;
$orders = [
['id' => 1, 'total' => 42.50, 'paid' => true],
['id' => 2, 'total' => 19.99, 'paid' => false],
['id' => 3, 'total' => 120.00, 'paid' => true],
];
$paid = array_filter($orders, fn (array $order): bool => $order['paid']);
$revenue = array_sum(array_column($paid, 'total'));
printf('%d paid orders, revenue %.2f%s', count($paid), $revenue, PHP_EOL);
echo json_encode(array_column($paid, 'id')), PHP_EOL;