<?php
/**
* Processes all the given items and returns an array with the results of the
* operation for each item. `null` indicates success and an Exception indicates
* an error. The keys of the result array match the keys of the $items array.
*
* @param array<string> $items
* @return array<null|Exception>
*/
#[\NoDiscard("as processing might fail for individual items")]
function bulk_process(array $items): array {
$results = [];
foreach ($items as $key => $item) {
if (\random_int(0, 9999) < 9999) {
// Pretend to do something useful with $item,
// which will succeed in 99.99% of cases.
echo "Processing {$item}", PHP_EOL;
$error = null;
} else {
$error = new \Exception("Failed to process {$item}.");
}
$results[$key] = $error;
}
return $results;
}
bulk_process($items);
?>
Output of the above example in PHP 8.5 is similar to:
Warning: The return value of function bulk_process() should either be used or intentionally ignored by casting it as (void), as processing might fail for individual items