PHP code example of koriym / loop

1. Go to this page and download the library: Download koriym/loop library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

koriym / loop example snippets


class User
{
    public function __construct(
        public readonly int $id,
        public readonly string $name
    ){}
}

// Database result sets or csv content
$resultSet = [ 
    ['id' => 1, 'name' => 'ray'],
    ['id' => 2, 'name' => 'bear'],
    ['id' => 3, 'name' => 'alps'],
];

/** @var Generator<Loop, User, mixed, void> $users */
$users = (new LoopGen)($resultSet, User::class);
foreach ($users as $user) {
    echo $user->name;
}

/** @var Loop $loop */
foreach ($users as $loop => $user) {
    echo match(true) {
        $loop->isFirst && $loop->isLast => "<ul><li>{$user->name}</ul>",
        $loop->isFirst => "<ul><li>{$user->name}",
        $loop->isLast => "<li>{$user->name}</ul>",
        default => "<li>{$user->name}"
    };
}

$dependencies = [
    $varName => $insntance,
    'dateTime' => new DateTime(), // DateTime instance is injected
];
$users = (new LoopGen)($resultSet, User::class, $dependencies);

class Row
{
    public function __construct(
        public readonly int $id,
        public readonly string $name
    ){}
}

// Retrieve contents of csv file as list<Row>
$csvIterator = new ogrrd\CsvIterator\CsvIterator($csvFilePath);
/** @var list<Row> $csvRowList */
$csvRowList = (new LoopGen)($csvIterator, Row::class);

foreach ($csvRowList as $loop => $row) {
    if ($loop->isFirst) {
        continue; // Skip header
    }
    echo $row->name;
}