Skip to content

Instantly share code, notes, and snippets.

@camspiers
Last active January 3, 2016 20:18
Show Gist options
  • Save camspiers/8513676 to your computer and use it in GitHub Desktop.
Save camspiers/8513676 to your computer and use it in GitHub Desktop.
<?php
function iterator_chunk($iterable, $size, $preserve_keys = false)
{
$chunk = [];
foreach ($iterable as $key => $value) {
if ($preserve_keys) {
$chunk[$key] = $value;
} else {
$chunk[] = $value;
}
if (\count($chunk) === $size) {
yield $chunk;
$chunk = [];
}
}
}
function iterator_column($iterable, $column_key, $index_key = null)
{
if ($index_key === null) {
foreach ($iterable as $value) {
yield $value[$column_key];
}
} else {
foreach ($iterable as $value) {
yield $value[$index_key] => $value[$column_key];
}
}
}
function iterator_combine($keys, $values)
{
foreach ($values as $value) {
yield $keys->current() => $value;
$keys->next();
}
}
function iterator_count_values($iterable)
{
$values = [];
foreach ($iterable as $value) {
if (empty($values[$value])) {
$values[$value] = 0;
}
$values[$value]++;
}
return $values;
}
function iterator_flip($iterable)
{
foreach ($iterable as $key => $value) {
yield $value => $key;
}
}
function count($iterable)
{
$count = 0;
foreach ($iterable as $_) {
$count++;
}
return $count;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment