29: Compiler Optimizations for array_map()
Overview
Section titled “Overview”Produce the same formatted prices with a first-class callable and a partially applied callback. PHP 8.6 can compile eligible array_map() calls into loops.
Prerequisites
Section titled “Prerequisites”- PHP 8.6 CLI. Confirm the version with
php --version. - Review the previous chapter if you’re following the series in order.
Allow about 10 minutes for the walkthrough and exercise.
What You’ll Build
Section titled “What You’ll Build”A runnable array-map-performance.php example.
Step 1: Run the example (~5 min)
Section titled “Step 1: Run the example (~5 min)”Run the following from the root of the Code with PHP repository.
php code/php-8-6/29-array-map-performance/array-map-performance.php<?php
declare(strict_types=1);
function formatPrice(float $price, float $factor = 1.2): string{ return sprintf('%.2f', $price * $factor);}
$prices = ['tea' => 5.0, 'coffee' => 7.5];$withCallable = array_map(formatPrice(...), $prices);$withPartial = array_map(formatPrice(?, 1.2), $prices);
echo json_encode($withCallable, JSON_THROW_ON_ERROR), PHP_EOL;echo 'Same prices: ', $withCallable === $withPartial ? 'yes' : 'no', PHP_EOL;Expected Result
Section titled “Expected Result”{"tea":"6.00","coffee":"9.00"}Same prices: yesWhy It Works
Section titled “Why It Works”A first-class callable has the form formatPrice(...). Partial application also exposes the target and fixed arguments at the call site. The optimization preserves the behavior of array_map(), including the index keys for a single input array.
Exercise
Section titled “Exercise”Change the multiplier from 1.2 to 1.5 in both paths and confirm the output arrays remain equal. To measure a real benefit, benchmark your own workload with the same PHP configuration and inputs.
Wrap-up
Section titled “Wrap-up”Continue with Faster printf() with Simple Formats.