1. Go to this page and download the library: Download bonami/collections 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/ */
bonami / collections example snippets
use Bonami\Collection\ArrayList;
class Person {
public function __construct(
private readonly string $name,
private readonly int $age
) {}
}
$persons = ArrayList::of(new Person('John', 31), new Person('Jacob', 22), new Person('Arthur', 29));
$names = $persons
->filter(fn (Person $person): bool => $person->age <= 30)
->sort(fn (Person $a, Person $b): int => $a->name <=> $b->name)
->map(fn (Person $person): string => $person->name)
->join(";");
// $names = "Arthur;Jacob"
use Bonami\Collection\ArrayList;
use Bonami\Collection\Map;
use function Bonami\Collection\identity;
use function Bonami\Collection\descendingComparator;
function frequencyAnalysis(string $text): Map {
$chars = preg_split('//u', $text, -1, PREG_SPLIT_NO_EMPTY);
return ArrayList::fromIterable($chars)
->groupBy(identity())
->mapValues(fn (ArrayList $group): int => $group->count());
}
$text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras nec mi rhoncus, dignissim tortor ac,' .
' aliquam metus. Maecenas non hendrerit tellus. Nam molestie augue ac lectus cursus consequat. Nunc ' .
'ultrices metus sit amet nulla blandit lacinia. Nam vestibulum ultrices mollis. Morbi consequat ante non ' .
'ornare lobortis. Nullam enim mauris, tempus quis auctor eu, condimentum dignissim nunc. Integer dapibus ' .
'dolor eu nisl euismod sagittis. Phasellus magna ante, pharetra eget nisi vehicula, elementum lacinia dui. ' .
'Aliquam semper at eros a sodales. In a rhoncus sapien. Integer blandit volutpat nisl. Donec vitae massa eget ' .
'mauris dignissim cursus nec et erat. Suspendisse consectetur ac quam sit amet pretium.';
// top ten characters by number of occurrences
$top10 = frequencyAnalysis($text)
->sortValues(descendingComparator())
->take(10);