phpfibers

PHP Fibers return null values


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] => 
)

Solution

  • The call to $fiber->start(); consumes your $val. As per documentation the return value of start() is the variable given to the first Fiber::suspend() call or null if the function returned. resume() does the same, so your call to start() already returned $val and then there is nothing left for resume().

    The result you want would be achieved with this code:

    <?php
      
    $data=["A","B","C"];
    $fibers = [];
    foreach ($data as $val) {
        $fiber = new Fiber(function () use ($val): void {
            Fiber::suspend();
            Fiber::suspend($val);
        });
    
        $fiber->start();
        $fibers[] = $fiber;
    }
    
    $results = [];
    foreach ($fibers as $fiber) {
        $results[] = $fiber->resume();
    }
    
    print_r($results);
    ?>
    

    And here a suggestion for a rewrite while still using Fiber:

    <?php
      
    $data=["A","B","C"];
    $fibers = [];
    
    $callback = function ($val): string {
        Fiber::suspend();
        return $val;
    };
    
    foreach ($data as $val) {
        $fiber = new Fiber($callback);
        $fiber->start($val);
        $fibers[] = $fiber;
    }
    
    $results = [];
    foreach ($fibers as $fiber) {
        $fiber->resume();
        $results[] = $fiber->getReturn();
    }
    
    print_r($results);
    ?>