PHP code example of xp-forge / sequence

1. Go to this page and download the library: Download xp-forge/sequence 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/ */

    

xp-forge / sequence example snippets


use util\data\{Sequence, Collectors, Aggregations};

$return= Sequence::of([1, 2, 3, 4])
  ->filter(fn($e) => 0 === $e % 2)
  ->toArray()
;
// $return= [2, 4]

$return= Sequence::of([1, 2, 3, 4])
  ->map(fn($e) => $e * 2)
  ->toArray()
;
// $return= [2, 4, 6, 8]

$i= 0;
$return= Sequence::of([1, 2, 3, 4])
  ->counting($i)
  ->reduce(0, fn($a, $b) => $a + $b)
;
// $i= 4, $return= 10

$names= Sequence::of($this->people)
  ->map('com.example.Person::name')
  ->collect(Collectors::joining(', '))
;
// $names= "Timm, Alex, Dude"

$experience= Sequence::of($this->employees)
  ->collect(Collectors::groupingBy(
    fn($e) => $e->department(),
    Aggregations::average(fn($e) => $e->years())
  ))
;
// $experience= util.collections.HashTable[2] {
//   Department("A") => 12.8
//   Department("B") => 3.5
// }

use util\data\Optional;

$first= Optional::of($repository->find($user));
if ($first->present()) {
  $user= $first->get();    // When Repository::find() returned non-null
}

$user= $first->orElse($this->currentUser);
$user= $first->orUse(fn() => $this->currentUser());

$name= $first
  ->filter(fn($user) => $user->isActive())
  ->whenAbsent($this->currentUser)
  ->whenAbsent(fn() => $this->guestUser())
  ->map('com.example.User::name')
  ->get()
;