Skip to content

Instantly share code, notes, and snippets.

@johnpbloch
Created June 20, 2016 16:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johnpbloch/b670f104787ce9cd1134cdfb320bdb28 to your computer and use it in GitHub Desktop.
Save johnpbloch/b670f104787ce9cd1134cdfb320bdb28 to your computer and use it in GitHub Desktop.
<?php
// Assuming https://wiki.php.net/rfc/arrow_functions makes it into PHP core, we can do this:
class Arr extends ArrayObject
{
static function make($array)
{
return new self($array);
}
function map($func)
{
$res = new self();
foreach ($this as $k => $v)
$res[$k] = $func($k, $v);
return $res;
}
function filter($func)
{
$res = new self();
foreach ($this as $k => $v)
if ($func($k, $v))
$res[$k] = $v;
return $res;
}
}
$nums = Arr::make([10, 20, 30, 40])
return $nums->filter( fn($v) => $v > 15 )->map( fn($v) => $v * 2 );
// Additionally, also there's this:
$x = rand(3,6);
return $nums->filter( fn($v) => $v > 15 )->map( fn($v) => $v * 2 + $x );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment