Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Cadrach's avatar

PHP 5.5 Generators & JSON

Hi everyone,

I am interested in using the PHP 5.5 Generators ( http://php.net/manual/en/language.generators.overview.php ) in Laravel, since I have some heavy data output to work with and would like to reduce the memory footprint of my calls.

Currently I am pushing the final array out, like so:

public function getSomeRoute(){
    $sql = "SELECT * ...";
    $stmt = DB::getPdo()->prepare($sql);
    $stmt->execute();
    while($row = $stmt->fetch()){
        //Do stuff to $row
        ....
        //Store $row in final array
        $array[] = $row;
    }

    return $array;
}

To use generator, I would like to not have to create the $array and return it, but would like to return directly the Generator maybe, that would then be parsed when rendering the JSON that is sent to the user.

Is there a way to do this? Or some way to hook into the JSON generation in order to allow for a Generator function to be used?

Thanks for reading,

0 likes
0 replies

Please or to participate in this conversation.