PHP code example of cocur / chain
1. Go to this page and download the library: Download cocur/chain 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/ */
cocur / chain example snippets
$arr = array_filter(
array_map(
function ($v) { return rand(0, $v); },
array_fill(0, 10, 20)
),
function ($v) { return $v & 1; }
);
$chain = Chain::fill(0, 10, 20)
->map(function ($v) { return rand(0, $v); })
->filter(function ($v) { return $v & 1; });
echo array_sum(array_intersect(
array_diff([1, 2, 3, 4, 5], [0, 1, 9]),
array_filter([2, 3, 4], function ($v) { return !($v & 1); })
));
echo Chain::create([1, 2, 3, 4, 5])
->diff([0, 1, 9])
->intersect(Chain::create([2, 3, 4])->filter(function ($v) { return !($v & 1); }))
->sum();
$chain = new Chain([1, 2, 3]);
$chain = Chain::create([1, 2, 3]);
$chain = Chain::fill(0, 10, 'foo');
Chain::createFromString(',', '1,2,3')->array; // -> [1, 2, 3]
Chain::createFromString('/,|.|;/', '1,2.3;4,5', ['regexp' => true])->array; // -> [1, 2, 3, 4, 5]
$chain = (new Chain([1, 2, 3]))
->map(function ($v) { return $v*3; })
->filter(function ($v) { return $v & 1; });
$chain->array; // -> [3, 9]
$chain = new Chain([1, 2, 3]);
$chain->array; // -> [1, 2, 3]
$chain = new Chain([1, 2, 3]);
foreach ($chain as $key => $value) {
// ...
}
$chain = new Chain();
$chain['foo'] = 'bar';
if (isset($chain['foo'])) {
echo $chain['foo'];
unset($chain['foo']);
}
$chain = new Chain([1, 2, 3]);
$chain->count(); // -> 3
$chain->sum(); // -> 6
$chain->first(); // -> 1
$chain->last(); // -> 3
$chain->reduce(function ($current, $value) {
return $current * $value;
}, 1); // -> 6