While running below code, it return empty values. I have used fibers to run the code and used PHP version is 8.2
<?php
$data=["A","B","C"];
$fibers = [];
foreach ($data as $val) {
$fiber = new Fiber(function () use ($val): void {
Fiber::suspend($val);
});
$fiber->start();
$fibers[] = $fiber;
}
$results = [];
foreach ($fibers as $fiber) {
$results[] = $fiber->resume();
}
print_r($results);
?>
Expected Output
Array
(
[0] =>"A"
[1] =>"B"
[2] =>"C"
)
While running above code return this output
Array
(
[0] =>
[1] =>
[2] =>
)
The call to
$fiber->start();consumes your$val. As per documentation the return value ofstart()is the variable given to the firstFiber::suspend()call or null if the function returned.resume()does the same, so your call tostart()already returned$valand then there is nothing left forresume().The result you want would be achieved with this code:
And here a suggestion for a rewrite while still using Fiber: