Part 3 · Flow & errors / When expressions
Lesson 6 of 8

When expressions

Express delivery charges by weight; standard delivery charges per parcel. Each when branch prepares the information its calculation needs, then returns a price in cents. Unlike match, the branches are statement blocks, so one can loop while another counts:

shipping.ppphp
<?php

// Parcel weights in kg; prices in cents.
array<int> $weights = [2, 5, 3];
bool $express = true;

readonly int $shipping = when ($express) {
    int $weight = 0;
    foreach ($weights as int $parcel) {
        $weight += $parcel;
    }
    return 1200 + $weight * 50;
} else {
    int $parcels = count($weights);
    return 500 + $parcels * 100;
};

echo $shipping;

An if/else chain would require declaring a variable and assigning it in each branch. Here, when initializes readonly int $shipping once, with no placeholder value. Both branches calculate a useful result.

Press Run to print 1700. Change $express to false and run again to print 800. Then change a parcel weight: express delivery changes, but standard delivery depends only on the number of parcels.

The final else supplies the standard-delivery result. A branch return supplies the value of when, not a return from the enclosing function. $weight and $parcels stay inside their branches; use $shipping afterwards. Press Build PHP to inspect the generated code.