PHP Lodash
php-lodash is a PHP utility library, similar to Underscore/Lodash, that utilizes `namespace`s and dynamic auto loading to improve library performance.
, (*1)
![Scrutinizer][scrutinizer-badge]
![downloads][downloads-badge]
![MIT License][license-badge]
, (*2)
![PRs Welcome][prs-badge]
![Code of Conduct][coc-badge]
![Watch on GitHub][github-watch-badge]
![Star on GitHub][github-star-badge]
[][twitter]
![Donate][donate-badge], (*3)
Table of Contents
Requirements
This library requires php php_mbstring
extension. To enable this extension open your php.ini
file and find for the line extension=php_mbstring.dll
and uncomment it. If this line is not there then manually add this line in php.ini
., (*4)
extension=php_mbstring.dll
Introduction
lodash-php
is a PHP utility library, similar to Underscore/Lodash
, that utilizes namespace
s and dynamic auto loading to improve library performance., (*5)
Project Structure
-
__.php
is the entry point for the lodash-php
utility library
- All lodash-php methods are stored in separate files within their respective
namespace
folder outlined in /src/__
- Tests reflect the
namespace
defined within the library and are processed using phpunit testing
- To run tests run the following command
phpunit
.
βββ images # Place relevant graphics in this folder
βββ src # Core code of the application.
β βββ __.php # Entry point for the library
β βββ Traits # Contains all lodash-php methods
β βββ Sequence\Chain.php # Methods related to chaining
β βββ Sequence\ChainWrapper.php # Methods related to chaining
β βββ Arrays.php # Methods related to arrays
β βββ Collections.php # Methods related to collections
β βββ Functions.php # Methods related to functions
β βββ Objects.php # Methods related to objects
β βββ Strings.php # Methods related to strings
β βββ Utilities.php # Methods related to utilities
βββ tests # Tests are placed in that folder.
βββ composer.json # This file defines the project requirements
βββ phpcs.xml.dist # Contains the configuration for PHPcs.
βββ phpstan.neon.dist # Contains the configuration for PHPStan.
βββ phpunit.xml.dist # Contains the configuration for PHPUnit.
βββ LICENSE # License file for `lodash-php`
βββ README.md # Introduces our library to user.
NOTE: lodash-php is not currently in feature parity with Underscore/Lodash. Review the contributing section for more information.
, (*6)
Installation
Just add me-io/php-lodash
to your project composer.json file:, (*7)
{
"require": {
"me-io/php-lodash": "^2"
}
}
and then run composer install. This will install me-io/php-lodash
and all it's dependencies. Or run the following command:, (*8)
composer require me-io/php-lodash
Usage
Arrays
Append item to array, (*9)
__::append([1, 2, 3], 4);
# [1, 2, 3, 4]
Returns a copy of the array with falsy values removed., (*10)
__::compact([0, 1, false, 2, '', 3]);
# [1, 2, 3]
Flattens a multidimensional array. If you pass shallow, the array will only be flattened a single level., (*11)
__::flatten([1, 2, [3, [4]]], [flatten]);
# [1, 2, 3, 4]
Patches array with list of xpath-value pairs., (*12)
__::patch(['addr' => ['country' => 'US', 'zip' => 12345]], ['/addr/country' => 'CA', '/addr/zip' => 54321]);
# ['addr' => ['country' => 'CA', 'zip' => 54321]]
__::prepend([1, 2, 3], 4);
# [4, 1, 2, 3]
Returns an array of integers from start to stop (exclusive) by step., (*13)
__::range(1, 10, 2);
# [1, 3, 5, 7, 9]
Returns an array of $n
length with each index containing the provided value., (*14)
__::repeat('foo', 3);
# ['foo', 'foo', 'foo']
Split an array into chunks, (*15)
__::chunk([1, 2, 3, 4, 5], 3);
# [[1, 2, 3], [4, 5]]
Creates a slice of array with n elements dropped from the beginning., (*16)
__::drop([0, 1, 3], 2);
# [3]
Shuffle an array ensuring no item remains in the same position., (*17)
__::randomize([1, 2, 3]);
# [2, 3, 1]
Search for the index of a value in an array., (*18)
__::search(['a', 'b', 'c'], 'b');
# 1
Returns the average value of an array., (*19)
__::average([1, 2, 3]);
# 2
Get the size of an array., (*20)
__::size([1, 2, 3]);
# 3
Check if an item is in an array., (*21)
__::contains(['a', 'b', 'c'], 'b');
# true
Clean all falsy values from an array., (*22)
__::clean([true, false, 0, 1, 'string', '']);
# [true, 1, 'string']
Get a random string from an array., (*23)
__::random([1, 2, 3]);
# Returns 1, 2 or 3
Return an array with all elements found in both input arrays., (*24)
__::intersection(["green", "red", "blue"], ["green", "yellow", "red"]);
# ["green", "red"]
Return a boolean flag which indicates whether the two input arrays have any common elements., (*25)
__::intersects(["green", "red", "blue"], ["green", "yellow", "red"])
# true
Exclude the last X elements from an array, (*26)
__::initial([1, 2, 3], 1);
# [1, 2]
Exclude the first X elements from an array, (*27)
__::rest([1, 2, 3], 2);
# [3]
Sort an array by key., (*28)
__::sortKeys(['z' => 0, 'b' => 1, 'r' => 2]);
# ['b' => 1, 'r' => 2, 'z' => 0]
__::sortKeys(['z' => 0, 'b' => 1, 'r' => 2], 'desc');
# ['z' => 0, 'r' => 2, 'b' => 1]
Remove unwanted values from array, (*29)
Returns new array without preserving keys., (*30)
__::without([1, 1 => 3, 2 => 4, 5], 4)
# [0 => 1, 1 => 3, 2 => 5]
Returns new array with preserving keys., (*31)
__::without([1, 3 => 3, 2 => 4, 5], 4, true)
# [0 => 1, 3 => 3, 4 => 5]
Chaining
Returns a wrapper instance, allows the value to be passed through multiple php-lodash functions, (*32)
__::chain([0, 1, 2, 3, null])
->compact()
->prepend(4)
->value();
# [4, 1, 2, 3]
Collections
Returns the values in the collection that pass the truth test., (*33)
$a = [
['name' => 'fred', 'age' => 32],
['name' => 'maciej', 'age' => 16]
];
__::filter($a, function($n) {
return $n['age'] > 24;
});
# [['name' => 'fred', 'age' => 32]]
Gets the first element of an array. Passing n returns the first n elements., (*34)
__::first([1, 2, 3, 4, 5], 2);
# [1, 2]
Get item of an array by index, aceepting nested index, (*35)
__::get(['foo' => ['bar' => 'ter']], 'foo.bar');
# 'ter'
Gets the last element of an array. Passing n returns the last n elements., (*36)
__::last([1, 2, 3, 4, 5], 2);
# [4, 5]
Returns an array of values by mapping each in collection through the iterator., (*37)
__::map([1, 2, 3], function($n) {
return $n * 3;
});
# [3, 6, 9]
Returns the maximum value from the collection. If passed an iterator, max will return max value returned by the iterator., (*38)
__::max([1, 2, 3]);
# 3
Returns the minimum value from the collection. If passed an iterator, min will return min value returned by the iterator., (*39)
__::min([1, 2, 3]);
# 1
Returns an array of values belonging to a given property of each item in a collection., (*40)
$a = [
['foo' => 'bar', 'bis' => 'ter' ],
['foo' => 'bar2', 'bis' => 'ter2'],
];
__::pluck($a, 'foo');
# ['bar', 'bar2']
Returns a collection of objects matching the given array of parameters., (*41)
$a = [
['name' => 'fred', 'age' => 32],
['name' => 'maciej', 'age' => 16]
];
__::where($a, ['age' => 16]);
# [['name' => 'maciej', 'age' => 16]]
Combines and merge collections provided with each others., (*42)
$a = [
'color' => [
'favorite' => 'red',
5
],
3
];
$b = [
10,
'color' => [
'favorite' => 'green',
'blue'
]
];
__::assign($a, $b);
# ['color' => ['favorite' => 'green', 'blue'], 10]
Reduces $collection to a value which is the $accumulator result of running each element in $collection - from right to left - thru $iteratee, where each successive invocation is supplied the return value of the previous., (*43)
__::reduceRight(['a', 'b', 'c'], function ($word, $char) {
return $word . $char;
}, '');
# 'cba'
Iterate over elements of the collection, from right to left, and invokes iterate for each element., (*44)
__::doForEachRight([1, 2, 3], function ($value) { print_r($value) });
# (Side effect: print 3, 2, 1)
Iterate over elements of the collection and invokes iterate for each element., (*45)
__::doForEach([1, 2, 3], function ($value) { print_r($value) });
# (Side effect: print 1, 2, 3)
Return a new collection with the item set at index to given value. Index can be a path of nested indexes., (*46)
__::set(['foo' => ['bar' => 'ter']], 'foo.baz.ber', 'fer');
# '['foo' => ['bar' => 'ter', 'baz' => ['ber' => 'fer']]]'
Returns if $input contains all requested $keys. If $strict is true it also checks if $input exclusively contains the given $keys., (*47)
__::hasKeys(['foo' => 'bar', 'foz' => 'baz'], ['foo', 'foz']);
# true
Return true if $collection contains the requested $key., (*48)
__::has(['foo' => ['bar' => 'num'], 'foz' => 'baz'], 'foo.bar');
# true
__::hasKeys((object) ['foo' => 'bar', 'foz' => 'baz'], 'bar');
# false
Combines and concat collections provided with each others., (*49)
__::concat(['color' => ['favorite' => 'red', 5], 3], [10, 'color' => ['favorite' => 'green', 'blue']]);
# ['color' => ['favorite' => ['green'], 5, 'blue'], 3, 10]
Recursively combines and concat collections provided with each others., (*50)
__::concatDeep(['color' => ['favorite' => 'red', 5], 3], [10, 'color' => ['favorite' => 'green', 'blue']]);
# ['color' => ['favorite' => ['red', 'green'], 5, 'blue'], 3, 10]
Flattens a complex collection by mapping each ending leafs value to a key consisting of all previous indexes., (*51)
__::ease(['foo' => ['bar' => 'ter'], 'baz' => ['b', 'z']]);
# '['foo.bar' => 'ter', 'baz.0' => 'b', , 'baz.1' => 'z']'
Checks if predicate returns truthy for all elements of collection., (*52)
__::every([1, 3, 4], function ($v) { return is_int($v); });
// β true
Returns an associative array where the keys are values of $key., (*53)
__::groupBy([
['state' => 'IN', 'city' => 'Indianapolis', 'object' => 'School bus'],
['state' => 'CA', 'city' => 'San Diego', 'object' => 'Light bulb'],
['state' => 'CA', 'city' => 'Mountain View', 'object' => 'Space pen'],
],
'state'
);
# [
# 'IN' => [
# ['state' => 'IN', 'city' => 'Indianapolis', 'object' => 'School bus'],
# ['state' => 'CA', 'city' => 'San Diego', 'object' => 'Light bulb'],
# ],
# 'CA' => [
# ['state' => 'CA', 'city' => 'Mountain View', 'object' => 'Space pen']
# ]
# ]
__::groupBy([
['state' => 'IN', 'city' => 'Indianapolis', 'object' => 'School bus'],
['state' => 'IN', 'city' => 'Indianapolis', 'object' => 'Manhole'],
['state' => 'CA', 'city' => 'San Diego', 'object' => 'Light bulb'],
],
function ($value) {
return $value->city;
}
);
# [
# 'Indianapolis' => [
# ['state' => 'IN', 'city' => 'Indianapolis', 'object' => 'School bus'],
# ['state' => 'IN', 'city' => 'Indianapolis', 'object' => 'Manhole'],
# ],
# 'San Diego' => [
# ['state' => 'CA', 'city' => 'San Diego', 'object' => 'Light bulb'],
# ]
# ]
Check if value is an empty array or object., (*54)
__::isEmpty([]);
# true
Recursively combines and merge collections provided with each others., (*55)
__::merge(['color' => ['favorite' => 'red', 'model' => 3, 5], 3], [10, 'color' => ['favorite' => 'green', 'blue']]);
# ['color' => ['favorite' => 'green', 'model' => 3, 'blue'], 10]
Returns an array having only keys present in the given path list., (*56)
__::pick(['a' => 1, 'b' => ['c' => 3, 'd' => 4]], ['a', 'b.d']);
# ['a' => 1, 'b' => ['d' => 4]]
Reduces $collection to a value which is the $accumulator result of running each element in $collection thru $iteratee, where each successive invocation is supplied the return value of the previous., (*57)
__::reduce([1, 2], function ($sum, $number) {
return $sum + $number;
}, 0);
# 3
$a = [
['state' => 'IN', 'city' => 'Indianapolis', 'object' => 'School bus'],
['state' => 'IN', 'city' => 'Indianapolis', 'object' => 'Manhole'],
['state' => 'IN', 'city' => 'Plainfield', 'object' => 'Basketball'],
['state' => 'CA', 'city' => 'San Diego', 'object' => 'Light bulb'],
['state' => 'CA', 'city' => 'Mountain View', 'object' => 'Space pen'],
];
$iteratee = function ($accumulator, $value) {
if (isset($accumulator[$value['city']]))
$accumulator[$value['city']]++;
else
$accumulator[$value['city']] = 1;
return $accumulator;
};
__::reduce($c, $iteratee, []);
# [
# 'Indianapolis' => 2,
# 'Plainfield' => 1,
# 'San Diego' => 1,
# 'Mountain View' => 1,
# ]
$object = new \stdClass();
$object->a = 1;
$object->b = 2;
$object->c = 1;
__::reduce($object, function ($result, $value, $key) {
if (!isset($result[$value]))
$result[$value] = [];
$result[$value][] = $key;
return $result;
}, [])
# [
# '1' => ['a', 'c'],
# '2' => ['b']
# ]
Builds a multidimensional collection out of a hash map using the key as indicator where to put the value., (*58)
__::unease(['foo.bar' => 'ter', 'baz.0' => 'b', , 'baz.1' => 'z']);
# '['foo' => ['bar' => 'ter'], 'baz' => ['b', 'z']]'
Strings
Split a string by string., (*59)
__::split('a-b-c', '-', 2);
# ['a', 'b-c']
Converts string to camel case., (*60)
__::camelCase('Foo Bar');
# 'fooBar'
Converts the first character of string to upper case and the remaining to lower case., (*61)
__::capitalize('FRED');
# 'Fred'
Converts string to kebab case., (*62)
__::kebabCase('Foo Bar');
# 'foo-bar'
Converts the first character of string to lower case, like lcfirst., (*63)
__::lowerFirst('Fred');
# 'fred'
Converts string to snake case., (*64)
__::snakeCase('Foo Bar');
# 'foo_bar'
Converts string to start case., (*65)
__::startCase('--foo-bar--');
# 'Foo Bar'
Converts string, as a whole, to lower case just like strtolower., (*66)
__::toLower('fooBar');
# 'foobar'
Converts string, as a whole, to lower case just like strtoupper., (*67)
__::toUpper('fooBar');
# 'FOOBAR'
Converts string, as space separated words, to upper case., (*68)
__::upperCase('--foo-bar');
# 'FOO BAR'
Converts the first character of string to upper case, like ucfirst., (*69)
__::upperFirst('fred');
# 'Fred'
Splits string into an array of its words., (*70)
__::words('fred, barney, & pebbles');
# ['fred', 'barney', 'pebbles']
__::words('fred, barney, & pebbles', '/[^, ]+/');
# ['fred', 'barney', '&', 'pebbles']
Converts string, as space separated words, to lower case., (*71)
__::lowerCase('--Foo-Bar--');
# 'foo bar'
Functions
__::slug('JakieΕ zdanie z duΕΌΔ
iloΕciΔ
obcych znakΓ³w!');
# 'jakies-zdanie-z-duza-iloscia-obcych-znakow'
$options = [
'delimiter' => '-',
'limit' => 30,
'lowercase' => true,
'replacements' => array(),
'transliterate' => true
]
__::slug('Something you don\'t know about know about Jackson', $options);
# 'something-you-dont-know-about'
Truncate string based on count of words, (*72)
$string = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque et mi orci.';
__::truncate($string);
# 'Lorem ipsum dolor sit amet, consectetur...'
__::truncate($string, 60);
# 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pel...'
Find the urls inside a string a put them inside anchor tags, (*73)
__::urlify('I love https://google.com');
# 'I love <a href="https://google.com">google.com</a>'
Objects
Check if give value is array or not., (*74)
__::isArray([1, 2, 3]);
# true
__::isArray(123);
# false
Check if give value is function or not., (*75)
__::isFunction(function ($a) { return $a + 2; });
# true
Check if give value is null or not., (*76)
__::isNull(null);
# true
Check if give value is number or not., (*77)
__::isNumber(123);
# true
Check if give value is object or not., (*78)
__::isObject('fred');
# false
Check if give value is string or not., (*79)
__::isString('fred');
# true
Utilities
Check if the value is valid email., (*80)
__::isEmail('test@test.com');
# true
__::isEmail('test_test.com');
# false
Wrapper of the time()
function that returns the current offset in seconds since the Unix Epoch., (*81)
__::now();
# 1417546029
Wrapper of the time()
function that returns the current offset in seconds since the Unix Epoch., (*82)
__::stringContains('waffle', 'wafflecone');
# true
Change log
Please see CHANGELOG for more information on what has changed recently., (*83)
Testing
bash
$ composer test
, (*84)
Contributing
Please feel free to contribute to this project! Pull requests and feature requests welcome! :v:, (*85)
Please see CONTRIBUTING and CODE_OF_CONDUCT for details., (*86)
Contributors
A huge thanks to all of our contributors:, (*87)
| 
Mohamed Meabed
π» β οΈ π’ | 
Zeeshan Ahmad
π» π β οΈ π |
| :---: | :---: |
, (*88)
License
The MIT License (MIT). Please see License File for more information., (*89)