PHP code example of krlove / collections
1. Go to this page and download the library: Download krlove/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/ */
krlove / collections example snippets
$sequence = Sequence::of('string');
$sequence->push('Gandalf');
$sequence->push('Bilbo');
$sequence->push('Frodo');
$sequence->remove(1);
foreach ($sequence as $index => $value) {
echo $index . ': ' . $value . PHP_EOL;
}
$map = Map::of('string', 'array');
$map->set('fruits', ['apple', 'banana', 'pear']);
$map->set('vegetables', ['tomato', 'potato', 'onion']);
$map->set('berries', ['strawberry', 'blueberry', 'raspberry']);
$map->remove('vegetables');
$map->set('berries', ['bilberry']);
foreach ($map as $key => $value) {
echo $key . ': ' . var_export($value, true) . PHP_EOL;
}
$set = Set::of('string');
$set->add('Gandalf');
$set->add('Bilbo');
$set->add('Bilbo');
echo var_export($set->toArray(), true) . PHP_EOL;
$sequence = Sequence::of('int');
$sequence->push('Gandalf');
$sequence = Sequence::of('?string');
$sequence->push(null);
$sequence = Sequence::of('string');
$sequence->push('Gandalf');
$sequence->freeze();
//$sequence->push('Bilbo'); Fatal error: Uncaught Krlove\Collection\Exception\FrozenException: Sequence is frozen and can not be changed
$copy = $sequence->copy();
$copy->push('Bilbo');
foreach ($copy as $index => $value) {
echo $index . ': ' . $value . PHP_EOL;
}
private Map<int, string> $map; // invalid
class MyClass
{
/**
* @var Map<int, string>
*/
private Map $map;
public function __construct()
{
$this->map = Map::of('int', 'string');
}
/**
* @param Map<int, string> $map
* @return void
*/
public function setMap(Map $map): void
{
if (!$map->isOf('int', 'string')) {
// throw exception
}
$this->map = $map;
}
}
fruits: array (
0 => 'apple',
1 => 'banana',
2 => 'pear',
)
berries: array (
0 => 'bilberry',
)
array (
0 => 'Gandalf',
1 => 'Bilbo',
)