Created
April 3, 2018 06:35
-
-
Save pierredup/13a95db3d9d9c9e5931895a1047b92dc to your computer and use it in GitHub Desktop.
Lodash-PHP example functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use function _\filter; | |
$users = [ | |
[ 'user' => 'barney', 'age' => 36, 'active' => true], | |
[ 'user' => 'fred', 'age' => 40, 'active' => false] | |
]; | |
filter($users, 'active'); | |
// => [[ 'user' => 'barney', 'age' => 36, 'active' => true]] | |
class User | |
{ | |
private $name; | |
private $active; | |
public function __construct(string $name, bool $active) | |
{ | |
$this->name = $name; | |
$this->active = $active; | |
} | |
public function isActive(): bool | |
{ | |
return $this->active; | |
} | |
} | |
$users = [ | |
new User('Barney', true), | |
new User('Fred', false), | |
]; | |
filter($users, 'active'); | |
/* => | |
[ | |
class User#219 (2) { | |
private $name => string(6) "Barney" | |
private $active => bool(true) | |
} | |
] | |
*. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use function _\orderBy; | |
$users = [ | |
['user' => 'fred', 'age' => 48], | |
['user' => 'barney', 'age' => 34], | |
['user' => 'fred', 'age' => 40], | |
['user' => 'barney', 'age' => 36] | |
]; | |
// Sort by `user` in ascending order and by `age` in descending order. | |
orderBy($users, ['user', 'age'], ['asc', 'desc']) | |
// => [['user' => 'barney', 'age' => 36], ['user' => 'barney', 'age' => 34], ['user' => 'fred', 'age' => 48], ['user' => 'fred', 'age' => 40]] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use function _\partition; | |
$users = [ | |
['user' => 'barney', 'age' => 36, 'active' => false], | |
['user' => 'fred', 'age' => 40, 'active' => true], | |
['user' => 'pebbles', 'age' => 1, 'active' => false] | |
]; | |
partition($users, function($user) { return $user['active']; }) | |
/* | |
=> | |
[ | |
[ | |
['user' => 'fred', 'age' => 40, 'active' => true] | |
], | |
[ | |
['user' => 'barney', 'age' => 36, 'active' => false], | |
['user' => 'pebbles', 'age' => 1, 'active' => false] | |
] | |
] | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment