, (*1)
A PHP library with commonly used code blocks for faster development, (*2)
Funct\firstValueNotEmpty($a, $b, $c)
, (*3)
, (*4)
Requirements
Installation
Via Composer, (*5)
``` bash
$ composer require funct/funct, (*6)
## Usage
The library consist of five groups: *Collection*, *Invoke*, *Object*, *Strings* and *General*. Each group has it's own namespace
suffix (Only *General* uses root namespace).
To include all group functions just include root namespace at the top of the file:
```PHP
use Funct;
For single group functions you have two options. One is to include root namespace and call directly with full namespace for e.g.:, (*7)
use Funct;
Funct\Strings\classify('hello world');
or to include only single group for e.g.:, (*8)
use Funct\Strings;
Strings\classify('hello world');
If you are using PHP >=5.6 you can include only single function. For e.g.:, (*9)
use function Funct\Strings\classify;
classify('hello world');
General
arrayKeyNotExists($key, array $array)
Checks if the given key or index exists in the array, (*10)
Funct\arrayKeyNotExists(2, [1, 2]); // => true
Funct\arrayKeyNotExists(1, [1, 2]); // => false
false($value)
Returns true if value is false, (*11)
Funct\false(false); // => true
Funct\false(true); // => false
firstValue($valueA)
Returns a first non null value from function arguments, (*12)
Funct\firstValue('foo_bar'); // => 'foo_bar'
Funct\firstValue(null, 'foo_bar'); // => 'foo_bar'
Funct\firstValue(null, null, 'foo_bar'); // => 'foo_bar'
firstValueNotEmpty($valueA, $valueB)
Returns a first not empty value from function arguments, (*13)
Funct\firstValueNotEmpty('foo_bar'); // => 'foo_bar'
Funct\firstValueNotEmpty('', 'foo_bar'); // => 'foo_bar'
Funct\firstValueNotEmpty('', null, 'foo_bar'); // => 'foo_bar'
ifSetOr($value, $default)
Return the first param if isset or the second one or null if it doesn't, (*14)
$bar = 'bar';
Funct\ifSetOr($foo); // => 'NULL'
Funct\ifSetOr($foo, 'foo_bar'); // => 'foo_bar'
Funct\ifSetOr($bar, 'foo_bar'); // => 'bar' ($bar value)
notEmpty($value)
Returns true if value is not empty, (*15)
Funct\notEmpty('fooBar'); // => true
Funct\notEmpty(''); // => false
notInArray($needle, $haystack, $strict = null)
Checks if needle is not in array, (*16)
Funct\notInArray(3, [0, 1, 2]); // => true
Funct\notInArray(2, [0, 1, 2]); // => false
notNull($value)
Returns true if value is not null, (*17)
Funct\notNull('fooBar'); // => true
Funct\notNull(null); // => false
null($value)
Returns true if value is null, (*18)
Funct\null(null); // => true
Funct\null('fooBar'); // => false
tempFile($prefix = 'php')
Generates temp file on systems temp folder with prefix, (*19)
Funct\tempFile('php'); // => /tmp/someFile.php
true($value)
Returns true if value is true, (*20)
Funct\true(true); // => true
Funct\true(false); // => false
Collection
compact($collection)
Returns a copy of the array with all falsy values removed, (*21)
Collection\compact([0, 1, false, 2, '', 3]); // => [1, 2, 3]
countBy($collection, $callback)
Sorts a array into groups and returns a count for the number of objects in each group. Similar to groupBy, but instead of
returning a array of values, returns a count for the number of values in that group, (*22)
Collection\countBy(
[1, 2, 3, 4, 5],
function ($value) {
return $value % 2 == 0 ? 'even': 'odd';
}
); // => ['odd' => 3, 'even' => 2]
Collection\countBy(
[
['color' => 'red', 'title' => 'Foo'],
['color' => 'red', 'title' => 'Foo'],
['color' => 'red', 'title' => 'Foo'],
['color' => 'blue', 'title' => 'Bar'],
['color' => 'blue', 'title' => 'Bar']
],
'color'
); // => ['red' => 3, 'blue => 2]
every($collection, callable $callback = null)
Returns true if all of the values in the array pass the callback truth test., (*23)
Collection\every([true, 1, null, 'yes']); // => false
Collection\every([true, 1, 'yes']); // => true
Collection\every(
[2, 4, 6],
function ($value) {
return ($value % 2) === 0;
}
); // => true
findWhere($collection, $value)
Looks through the array and returns the first value that matches all of the key-value pairs listed in properties., (*24)
Collection\findWhere(
[
['title' => 'Book of Fooos', 'author' => 'FooBar', 'year' => 1111],
['title' => 'Cymbeline', 'author' => 'Shakespeare', 'year' => 1611],
['title' => 'The Tempest', 'author' => 'Shakespeare', 'year' => 1611],
['title' => 'Book of Foos Barrrs', 'author' => 'FooBar', 'year' => 2222],
['title' => 'Still foooing', 'author' => 'FooBar', 'year' => 3333],
['title' => 'Happy Foo', 'author' => 'FooBar', 'year' => 4444],
],
['author' => 'Shakespeare', 'year' => 1611]
); // => ['title' => 'Cymbeline', 'author' => 'Shakespeare', 'year' => 1611]
first($collection)
First value of collection, (*25)
Collection\first([1, 2, 3]); // => 1
firstN($collection, $n = 1)
Collection\firstN([1, 2, 3]); // => [1]
Collection\firstN([1, 2, 3], 2); // => [1, 2]
flatten($collection, $depth = 1)
Flattens a nested array by depth., (*26)
Collection\flatten(['a', ['b', ['c', ['d']]]]); // => ['a', 'b', ['c', ['d']]]
Collection\flatten(['a', ['b', ['c', ['d']]]], 2); // => ['a', 'b', 'c', ['d']]
Collection\flatten(['a', ['b', ['c', ['d']]]], 3); // => ['a', 'b', 'c', 'd']
flattenAll($collection)
Flattens all arrays to single level, (*27)
Collection\flattenAll(['a', ['b', ['c', ['d']]]]); // => ['a', 'b', 'c', 'd']
forEvery($collection, $callable)
Alias of invoke($collection, $callable), (*28)
get($collection, $key, $default = null)
Returns item from collection if exists otherwise null or default value, (*29)
$collection = ['red' => []];
$collection['blue'] = Collection\get($collection, 'blue', []);
$collection['blue'][] = 'Hello World';
Collection\get($collection, 'red', ['empty']);
groupBy($collection, $callback)
Splits a collection into sets, grouped by the result of running each value through callback. If callback is a string, (*30)
Collection\groupBy([1.3, 2.1, 2.4], function($num) { return floor($num); }); // => [1 => [1.3], 2 => [2.1, 2.4]]
Collection\groupBy(['one', 'two', 'three'], 'strlen'); // => [3 => ["one", "two"], 5 => ["three"]]
initial($collection, $n = 1)
Returns everything but the last entry of the array. Especially useful on the arguments object. Pass n to exclude the, (*31)
Collection\initial([5, 4, 3, 2, 1]); // => [5, 4, 3, 2]
Collection\initial([5, 4, 3, 2, 1], 2); // => [5, 4, 3]
intersection($collectionFirst, $collectionSecond)
Computes the list of values that are the intersection of all the arrays. Each value in the result is present in each, (*32)
Collection\intersection([1, 2, 3], [101, 2, 1, 10], [2, 1]); // => [1, 2]
invoke($collection, callable $callback)
Invokes callback on each value in the list. Any extra arguments passed will be forwarded on to the method invocation., (*33)
Collection\invoke(['a', 'b', 'c'], 'strtoupper'); // => ['A', 'B', 'C']
last($collection)
Returns last element of array, (*34)
Collection\last([1, 2, 3]); // => 3
lastIndexOf($collection, $value)
Returns the index of the last occurrence of value in the array, or false if value is not present, (*35)
Collecton\lastIndexOf([1, 2, 3, 1, 2, 3], 2); // => 4
lastN($collection, $n = 1)
Returns the last element of an array. Passing n will return the last n elements of the array., (*36)
Collection\lastN([1, 2, 3]); // => [3]
Collection\lastN([1, 2, 3], 2); // => [2, 3]
maxValue($collection, callable $callback)
Returns the maximum value in collection using callback method, (*37)
Collection\maxValue(
[
10 => [
'title' => 'a',
'size' => 1
],
20 => [
'title' => 'b',
'size' => 2
],
30 => [
'title' => 'c',
'size' => 3
]
],
function ($item) {
return $item['size'];
}
); // => [
'title' => 'c',
'size' => 3
]
merge(&$a, $b)
Merges all arrays to first array, (*38)
$array = [1, 2];
Collection\merge($array, [3, 4], [5, 6]);
$array // => [1, 2, 3, 4, 5, 6];
minValue($collection, callable $callback)
Returns the minimum value in collection using callback method, (*39)
Collection\minValue(
[
10 => [
'title' => 'a',
'size' => 1
],
20 => [
'title' => 'b',
'size' => 2
],
30 => [
'title' => 'c',
'size' => 3
]
],
function ($item) {
return $item['size'];
}
); // => [
'title' => 'a',
'size' => 1
]
pairs($collection)
Convert an array into a list of [key, value] pairs., (*40)
Collection\pairs([1, 2, 3]); // => [[0, 1], [1, 2], [2, 3]]
partition($collection, callable $callback)
Split array into two arrays: one whose elements all satisfy callback and one whose elements all do not satisfy, (*41)
Collection\partition([1, 2, 3, 4, 5, 6, 7, 8, 9], function ($num) { return $num % 2 === 0; }); // => [[0, 2, 4, 6, 8], [1, 3, 5, 7, 9]]
pluck($collection, $key)
Extract single property from array of arrays, (*42)
Collection\pluck(
[
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
],
0
); // => [1, 4, 7]
reject($collection, callable $callback)
Returns the values in array without the elements that the truth test callback passes. The opposite of array_filter., (*43)
Collection\reject([1, 2, 3, 4, 5, 6], function($num) { return $num % 2 == 0; }); // => [1, 3, 5]
rest($collection, $from = 1)
Returns the rest of the elements in an array. Pass an from to return the values of the array from that index onward., (*44)
Collection\rest([5, 4, 3, 2, 1]); // => [4, 3, 2, 1]
reverse($collection, $preserveNumericKeys)
Reverses an array., (*45)
Collection\reverse(['a', 'b', 'c']); // ['c', 'b', 'a']
Collection\reverse(['php', 7.0, ['green', 'red']], true); // [2 => [0 => 'green', 1 => 'red'], 1 => 7.0, 0 => 'php']
size($collection, $countRecursive)
Computes the size of a collection, i.e., count all elements in a collection, (*46)
Collection\size(['a', 'b', 'c']); // 3
Collection\size(['a', 'b', 'c', ['d', 'e']], true); // 6
some($collection, callable $callback = null)
Returns true if any of the values in the array pass the callback truth test., (*47)
Collection\some([null, 0, 'yes', false]); // => true
sortBy($collection, $sortBy, $sortFunction = 'asort')
Returns a sorted array by callback function which should return value to which sort, (*48)
Collection\sortBy([1, 2, 3, 4, 5, 6], function ($num) { return sin($num); }); // => [5, 4, 6, 3, 1, 2]
tail($collection, $from = 1)
Alias of rest($collection, $from = 1), (*49)
toJson($collection)
Returns the JSON representation of a collection, (*50)
Collection\toJson(['a' => 1, 'b' => 2, 'c' => 3]); // {"a":1,"b":2,"c":3}
union($collectionFirst, $collectionSecond)
Computes the union of the passed-in arrays: the list of unique items, in order, that are present in one or more of, (*51)
Collection\union([1, 2, 3], [101, 2, 1, 10], [2, 1]); // => [1, 2, 3, 101, 10]
unzip($collection)
The opposite of zip. Given a number of arrays, returns a series of new arrays, the first of which contains all of, (*52)
Collection\unzip([['moe', 'larry', 'curly'], [30, 40, 50], [true, false, false]]); // => ["moe", 30, true], ["larry", 40, false], ["curly", 50, false]
where($collection, $value)
Looks through each value in the array, returning an array of all the values that contain all of the key-value pairs, (*53)
Collection\findWhere(
[
['title' => 'Book of Fooos', 'author' => 'FooBar', 'year' => 1111],
['title' => 'Cymbeline', 'author' => 'Shakespeare', 'year' => 1611],
['title' => 'The Tempest', 'author' => 'Shakespeare', 'year' => 1611],
['title' => 'Book of Foos Barrrs', 'author' => 'FooBar', 'year' => 2222],
['title' => 'Still foooing', 'author' => 'FooBar', 'year' => 3333],
['title' => 'Happy Foo', 'author' => 'FooBar', 'year' => 4444],
],
['author' => 'Shakespeare', 'year' => 1611]
); // => [
1 => ['title' => 'Cymbeline', 'author' => 'Shakespeare', 'year' => 1611],
2 => ['title' => 'The Tempest', 'author' => 'Shakespeare', 'year' => 1611]
]
without($collection, $without)
Returns a copy of the array with all instances of the values removed., (*54)
Collection\without([1, 2, 1, 0, 3, 1, 4], 0, 1); // => [2, 3, 4]
zip($collectionFirst, $collectionSecond)
Merges together the values of each of the arrays with the values at the corresponding position., (*55)
Collection\zip(['moe', 'larry', 'curly'], [30, 40, 50], [true, false, false]); // => [["moe", 30, true], ["larry", 40, false], ["curly", 50, false]]
String
Extracts the string between two substrings, (*56)
Strings\between('<a>foo</a>', '<a>', '</a>'); // => 'foo'
Strings\between('<a>foo</a></a>', '<a>', '</a>'); // => 'foo'
Strings\between('<a><a>foo</a></a>', '<a>', '</a>'); // => '<a>foo'
Strings\between('<a>foo', '<a>', '</a>'); // => ''
Strings\between('Some strings } are very {weird}, dont you think?', '{', '}'); // => 'weird'
Strings\between('This is a test string', 'test'); // => ' string'
Strings\between('This is a test string', '', 'test'); // => 'This is a '
Camelizes string, (*57)
Strings\camelize('data_rate'); //'dataRate'
Strings\camelize('background-color'); //'backgroundColor'
Strings\camelize('-moz-something'); //'mozSomething'
Strings\camelize('_car_speed_'); //'carSpeed'
Strings\camelize('yes_we_can'); //'yesWeCan'Strings\camelize(
Removes prefix from start of string, (*58)
Strings\chompLeft('foobar', 'foo'); //'bar'
Strings\chompLeft('foobar', 'bar'); //'foobar'
Removes suffix from end of string, (*59)
Strings\chompRight('foobar', 'bar'); // => 'foo'
Strings\chompRight('foobar', 'foo'); // => 'foobar'
classify($string)
Converts string to camelized class name. First letter is always upper case, (*60)
Strings\classify('className'); // => ClassName
Collapse multiple spaces, (*61)
Strings\collapseWhitespace(" String \t libraries are \n\n\t fun\n! "); // => 'String libraries are fun !'
Check if string contains substring, (*62)
Strings\contains('PHP is one of the best languages!', 'one'); // => true
Count the occurrences of substring in string, (*63)
Strings\countOccurrences('AN likes to program. AN does not play in the NBA.', "AN"); // => 2
Strings\countOccurrences('Does not exist.', "Flying Spaghetti Monster"); // => 0
Strings\countOccurrences('Does not exist.', "Bigfoot"); // => 0
Strings\countOccurrences('PHP is fun, therefore Node.js is fun', "fun"); // => 2
Strings\countOccurrences('funfunfun', "fun"); // => 3
dasherize($string)
Converts hyphens and camel casing to dashes, (*64)
Strings\dasherize('dataRate'); // => 'data-rate'
Strings\dasherize('CarSpeed'); // => 'car-speed'
Strings\dasherize('yesWeCan'); // => 'yes-we-can'
Strings\dasherize('backgroundColor'); // => 'background-color'
Check if string ends with substring, (*65)
Strings\endsWith("hello jon", 'jon'); // => true
Alias of contains, (*66)
Check if string contains only letters, (*67)
Strings\isAlpha("afaf"); // => true
Strings\isAlpha('fdafaf3'); // => false
Strings\isAlpha('dfdf--dfd'); // => false
Check if string contains only alphanumeric, (*68)
Strings\isAlphaNumeric("afaf35353afaf"); // => true
Strings\isAlphaNumeric("FFFF99fff"); // => true
Strings\isAlphaNumeric("99"); // => true
Strings\isAlphaNumeric("afff"); // => true
Strings\isAlphaNumeric("Infinity"); // => true
Strings\isAlphaNumeric("-Infinity"); // => false
Strings\isAlphaNumeric("-33"); // => false
Strings\isAlphaNumeric("aaff.."); // => false
Checks if letters in given string are all lowercase., (*69)
Strings\isLower('a'); // => true
Strings\isLower('z'); // => true
Strings\isLower('B'); // => false
Strings\isLower('hiAN'); // => true
Strings\isLower('hi AN'); // => false
Strings\isLower('HelLO'); // => false
Check if string contains only digits, (*70)
Strings\isNumeric("3"); // => true
Strings\isNumeric("34.22"); // => false
Strings\isNumeric("-22.33"); // => false
Strings\isNumeric("NaN"); // => false
Strings\isNumeric("Infinity"); // => false
Strings\isNumeric("-Infinity"); // => false
Strings\isNumeric("AN"); // => false
Strings\isNumeric("-5"); // => false
Strings\isNumeric("000992424242"); // => true
Checks if letters in given string are all uppercase., (*71)
Strings\isUpper('a'); // => false
Strings\isUpper('z'); // => false
Strings\isUpper('B'); // => true
Strings\isUpper('HIAN'); // => true
Strings\isUpper('HI AN'); // => false
Strings\isUpper('HelLO'); // => true
Remove accents from latin characters, (*72)
Strings\latinize('crÚme brûlée'); // => 'creme brulee'
left($string, $n)
Return the substring denoted by n positive left-most characters, (*73)
Strings\left('My name is AN', 2); // => 'My'
Strings\left('Hi', 0); // => ''
Strings\left('My name is AN', -2); // => 'AN', same as right(2)
Alias of length($input, $mb = false);, (*74)
Get string length., (*75)
Strings\length('rod'); // 3
Strings\length('marçal'); // 7
Strings\length('marçal', true); // 6
lines($string)
Returns an array with the lines. Cross-platform compatible, (*76)
Strings\lines("My name is AN\nPHP is my fav language\r\nWhat is your fav language?"); // => [ 'My name is AN',
'PHP is my fav language',
'What is your fav language?' ]
Converts string first char to lowercase, (*77)
Strings\lowerCaseFirst('HelloWorld'); // => 'helloWorld
pad($string, $length, $char = ' ')
Pads the string in the center with specified character. char may be a string or a number, defaults is a space, (*78)
Strings\pad('hello', 5); // 'hello'
Strings\pad('hello', 10); // ' hello '
Strings\pad('hey', 7); // ' hey '
Strings\pad('hey', 5); // ' hey '
Strings\pad('hey', 4); // ' hey'
Strings\pad('hey', 7, '-');// '--hey--'
Left pads the string, (*79)
Strings\padLeft('hello', 5); // => 'hello'
Strings\padLeft('hello', 10); // => ' hello'
Strings\padLeft('hello', 7); // => ' hello'
Strings\padLeft('hello', 6); // => ' hello'
Strings\padLeft('hello', 10, '.'); // => '.....hello'
Right pads the string, (*80)
Strings\padRight('hello', 5); // => 'hello'
Strings\padRight('hello', 10); // => 'hello '
Strings\padRight('hello', 7); // => 'hello '
Strings\padRight('hello', 6); // => 'hello '
Strings\padRight('hello', 10, '.'); // => 'hello.....'
Alias times($input, $n), (*81)
Reverses a string, (*82)
Strings\reverse('hello world'); // => dlrow olleh
right($string, $n)
Return the substring denoted by n positive right-most characters, (*83)
Strings\right('I AM CRAZY', 2); // => 'ZY'
Strings\right('Does it work? ', 4); // => 'k? '
Strings\right('Hi', 0); // => ''
Strings\right('My name is AN', -2); // => 'My', same as left(2)
slugify($string)
Converts the text into a valid url slug. Removes accents from Latin characters, (*84)
Strings\slugify('Global Thermonuclear Warfare'); // => 'global-thermonuclear-warfare'
Strings\slugify('CrÚme brûlée'); // => 'creme-brulee'
Check if string starts with substring, (*85)
Strings\startsWith("AN is a software engineer", "AN"); // => true
Strings\startsWith('wants to change the world', "politicians"); // => false
strip($string, $string1)
Returns a new string with all occurrences of [string1],[string2],... removed., (*86)
Strings\strip(' 1 2 3--__--4 5 6-7__8__9--0', ' ', '_', '-'); // => '1234567890'
Strings\strip('can words also be stripped out?', 'words', 'also', 'be'); // => 'can stripped out?'
stripPunctuation($string)
Strip all of the punctuation, (*87)
Strings\stripPunctuation('My, st[ring] *full* of %punct)'); // => 'My string full of punct'
swapCase($string, $mb = false)
Returns a case swapped version of the string, (*88)
Strings\swapCase('RoD eLIas'); // rOd EliAS
Repeat the string n times, (*89)
Strings\times(' ', 3); // => ' '
Strings\times('*', 3); // => '***'
titleize($string, array $ignore = [])
Creates a title version of the string. Capitalizes all the words and replaces some characters in the string to, (*90)
Strings\titleize('hello world'); // => 'Hello World'
toSentence($array, $delimiter = ', ', $lastDelimiter = ' and ')
Join an array into a human readable sentence, (*91)
Strings\toSentence(["A", "B", "C"]); // => "A, B and C";
Strings\toSentence(["A", "B", "C"], ", ", " ir "); // => "A, B ir C";
toSentenceSerial($array, $delimiter = ', ', $lastDelimiter = 'and ')
The same as string_to_sentence, but adjusts delimeters to use Serial comma), (*92)
Strings\toSentenceSerial(["A", "B"]); // => "A and B"
Strings\toSentenceSerial(["A", "B", "C"]); // => "A, B, and C"
Strings\toSentenceSerial(["A", "B", "C"], ", ", " unt "); // => "jQuery, Mootools, unt Prototype"
Makes a string lowercase;, (*93)
Strings\toLower('ROD ELIAS'); // rod elias
Makes a string uppercase;, (*94)
Strings\toUpper('rod elias'); // ROD ELIAS
Truncate string accounting for word placement and character count, (*95)
Strings\truncate('this is some long text', 3); // => '...'
Strings\truncate('this is some long text', 7); // => 'this is...'
Strings\truncate('this is some long text', 11); // => 'this is...'
Strings\truncate('this is some long text', 12); // => 'this is some...'
Strings\truncate('this is some long text', 11); // => 'this is...'
Strings\truncate('this is some long text', 14, ' read more'); // => 'this is some read more'
underscore($string)
Converts hyphens and camel casing to underscores, (*96)
Strings\underscore('dataRate'); // => 'data_rate'
Strings\underscore('CarSpeed'); // => 'car_speed'
Strings\underscore('yesWeCan'); // => 'yes_we_can'
Converts string first char to uppercase, (*97)
Strings\upperCaseFirst('helloWorld'); // => 'HelloWorld
Invoke
ifCondition(callable $callable, $methodArguments = [], $condition)
Invoke a method if condition is true, (*98)
Invoke\ifCondition(function () { echo 'Hello World'; }, [], Funct\notEmpty('Hello?')); // => Hello World
ifIsset(callable $callable, $values, $key)
Invoke a method if value isset, (*99)
Invoke\ifIsset(function () { echo 'Hello World'; }, ['Hello' = > 1000], 'Hello'); // => Hello World
ifNotEmpty(callable $callable, $var)
Invoke a method if value is not empty, (*100)
Invoke\ifNotEmpty(function () { echo 'Hello World'; }, 'Hello'); // => Hello World
Object
toArray($objects, $valueMethod, $keyMethod = null)
Creates array from objects using valueMethod as value and with/without keyMethod as key, (*101)
Object\toArray($objects, 'getValue', 'getkey'); // => ['key' => 'value']
assignIfIsset($object, $property, $array, $key)
Assign value to object from array if key exists, (*102)
$array = ['bar' => 'foobar'];
Object\assignIfIsset($object, 'foo', $array, 'bar'); // => $object->foo = 'foobar'
Testing
bash
$ composer test
, (*103)
Contributing
Please see CONTRIBUTING and CONDUCT for details., (*104)
License
Please see License File for more information., (*105)