A PHP library with commonly used code blocks for faster development
Funct\firstValueNotEmpty($a, $b, $c)
- Requirements
- Installation
- Usage
- Library
- General
- Collection
- String
- between
- camelize
- chompLeft
- chompRight
- classify
- collapseWhitespace
- contains
- countOccurrences
- dasherize
- endsWith
- includes
- isAlpha
- isAlphaNumeric
- isLower
- isNumeric
- isUpper
- latinize
- left
- len
- length
- lines
- lowerCaseFirst
- pad
- padLeft
- padRight
- repeat
- reverse
- right
- slugify
- startsWith
- strip
- stripPunctuation
- swapCase
- times
- titleize
- toSentence
- toSentenceSerial
- toLower
- toUpper
- truncate
- underscore
- upperCaseFirst
- Invoke
- Object
- Testing
- Contributing
- License
- PHP >= 5.5
Via Composer
$ composer require funct/funct
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:
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.:
use Funct;
Funct\Strings\classify('hello world');
or to include only single group for e.g.:
use Funct\Strings;
Strings\classify('hello world');
If you are using PHP >=5.6 you can include only single function. For e.g.:
use function Funct\Strings\classify;
classify('hello world');
Checks if the given key or index exists in the array
Funct\arrayKeyNotExists(2, [1, 2]); // => true
Funct\arrayKeyNotExists(1, [1, 2]); // => false
Returns true if value is false
Funct\false(false); // => true
Funct\false(true); // => false
Returns a first non null value from function arguments
Funct\firstValue('foo_bar'); // => 'foo_bar'
Funct\firstValue(null, 'foo_bar'); // => 'foo_bar'
Funct\firstValue(null, null, 'foo_bar'); // => 'foo_bar'
Returns a first not empty value from function arguments
Funct\firstValueNotEmpty('foo_bar'); // => 'foo_bar'
Funct\firstValueNotEmpty('', 'foo_bar'); // => 'foo_bar'
Funct\firstValueNotEmpty('', null, 'foo_bar'); // => 'foo_bar'
Return the first param if isset or the second one or null if it doesn't
$bar = 'bar';
Funct\ifSetOr($foo); // => 'NULL'
Funct\ifSetOr($foo, 'foo_bar'); // => 'foo_bar'
Funct\ifSetOr($bar, 'foo_bar'); // => 'bar' ($bar value)
Returns true if value is not empty
Funct\notEmpty('fooBar'); // => true
Funct\notEmpty(''); // => false
Checks if needle is not in array
Funct\notInArray(3, [0, 1, 2]); // => true
Funct\notInArray(2, [0, 1, 2]); // => false
Returns true if value is not null
Funct\notNull('fooBar'); // => true
Funct\notNull(null); // => false
Returns true if value is null
Funct\null(null); // => true
Funct\null('fooBar'); // => false
Generates temp file on systems temp folder with prefix
Funct\tempFile('php'); // => /tmp/someFile.php
Returns true if value is true
Funct\true(true); // => true
Funct\true(false); // => false
Returns a copy of the array with all falsy values removed
Collection\compact([0, 1, false, 2, '', 3]); // => [1, 2, 3]
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
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]
Returns true if all of the values in the array pass the callback truth test.
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
Looks through the array and returns the first value that matches all of the key-value pairs listed in properties.
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 value of collection
Collection\first([1, 2, 3]); // => 1
Collection\firstN([1, 2, 3]); // => [1]
Collection\firstN([1, 2, 3], 2); // => [1, 2]
Flattens a nested array by depth.
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']
Flattens all arrays to single level
Collection\flattenAll(['a', ['b', ['c', ['d']]]]); // => ['a', 'b', 'c', 'd']
Alias of invoke($collection, $callable)
Returns item from collection if exists otherwise null or default value
$collection = ['red' => []];
$collection['blue'] = Collection\get($collection, 'blue', []);
$collection['blue'][] = 'Hello World';
Collection\get($collection, 'red', ['empty']);
Splits a collection into sets, grouped by the result of running each value through callback. If callback is a string
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"]]
Returns everything but the last entry of the array. Especially useful on the arguments object. Pass n to exclude the
Collection\initial([5, 4, 3, 2, 1]); // => [5, 4, 3, 2]
Collection\initial([5, 4, 3, 2, 1], 2); // => [5, 4, 3]
Computes the list of values that are the intersection of all the arrays. Each value in the result is present in each
Collection\intersection([1, 2, 3], [101, 2, 1, 10], [2, 1]); // => [1, 2]
Invokes callback on each value in the list. Any extra arguments passed will be forwarded on to the method invocation.
Collection\invoke(['a', 'b', 'c'], 'strtoupper'); // => ['A', 'B', 'C']
Returns last element of array
Collection\last([1, 2, 3]); // => 3
Returns the index of the last occurrence of value in the array, or false if value is not present
Collecton\lastIndexOf([1, 2, 3, 1, 2, 3], 2); // => 4
Returns the last element of an array. Passing n will return the last n elements of the array.
Collection\lastN([1, 2, 3]); // => [3]
Collection\lastN([1, 2, 3], 2); // => [2, 3]
Returns the maximum value in collection using callback method
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
]
Merges all arrays to first array
$array = [1, 2];
Collection\merge($array, [3, 4], [5, 6]);
$array // => [1, 2, 3, 4, 5, 6];
Returns the minimum value in collection using callback method
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
]
Convert an array into a list of [key, value] pairs.
Collection\pairs([1, 2, 3]); // => [[0, 1], [1, 2], [2, 3]]
Split array into two arrays: one whose elements all satisfy callback and one whose elements all do not satisfy
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]]
Extract single property from array of arrays
Collection\pluck(
[
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
],
0
); // => [1, 4, 7]
Returns the values in array without the elements that the truth test callback passes. The opposite of array_filter.
Collection\reject([1, 2, 3, 4, 5, 6], function($num) { return $num % 2 == 0; }); // => [1, 3, 5]
Returns the rest of the elements in an array. Pass an from to return the values of the array from that index onward.
Collection\rest([5, 4, 3, 2, 1]); // => [4, 3, 2, 1]
Reverses an array.
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']
Computes the size of a collection, i.e., count all elements in a collection
Collection\size(['a', 'b', 'c']); // 3
Collection\size(['a', 'b', 'c', ['d', 'e']], true); // 6
Returns true if any of the values in the array pass the callback truth test.
Collection\some([null, 0, 'yes', false]); // => true
Returns a sorted array by callback function which should return value to which sort
Collection\sortBy([1, 2, 3, 4, 5, 6], function ($num) { return sin($num); }); // => [5, 4, 6, 3, 1, 2]
Alias of rest($collection, $from = 1)
Returns the JSON representation of a collection
Collection\toJson(['a' => 1, 'b' => 2, 'c' => 3]); // {"a":1,"b":2,"c":3}
Computes the union of the passed-in arrays: the list of unique items, in order, that are present in one or more of
Collection\union([1, 2, 3], [101, 2, 1, 10], [2, 1]); // => [1, 2, 3, 101, 10]
The opposite of zip. Given a number of arrays, returns a series of new arrays, the first of which contains all of
Collection\unzip([['moe', 'larry', 'curly'], [30, 40, 50], [true, false, false]]); // => ["moe", 30, true], ["larry", 40, false], ["curly", 50, false]
Looks through each value in the array, returning an array of all the values that contain all of the key-value pairs
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]
]
Returns a copy of the array with all instances of the values removed.
Collection\without([1, 2, 1, 0, 3, 1, 4], 0, 1); // => [2, 3, 4]
Merges together the values of each of the arrays with the values at the corresponding position.
Collection\zip(['moe', 'larry', 'curly'], [30, 40, 50], [true, false, false]); // => [["moe", 30, true], ["larry", 40, false], ["curly", 50, false]]
Extracts the string between two substrings
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
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
Strings\chompLeft('foobar', 'foo'); //'bar'
Strings\chompLeft('foobar', 'bar'); //'foobar'
Removes suffix from end of string
Strings\chompRight('foobar', 'bar'); // => 'foo'
Strings\chompRight('foobar', 'foo'); // => 'foobar'
Converts string to camelized class name. First letter is always upper case
Strings\classify('className'); // => ClassName
Collapse multiple spaces
Strings\collapseWhitespace(" String \t libraries are \n\n\t fun\n! "); // => 'String libraries are fun !'
Check if string contains substring
Strings\contains('PHP is one of the best languages!', 'one'); // => true
Count the occurrences of substring in string
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
Converts hyphens and camel casing to dashes
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
Strings\endsWith("hello jon", 'jon'); // => true
Alias of contains
Check if string contains only letters
Strings\isAlpha("afaf"); // => true
Strings\isAlpha('fdafaf3'); // => false
Strings\isAlpha('dfdf--dfd'); // => false
Check if string contains only alphanumeric
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.
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
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.
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
Strings\latinize('crème brûlée'); // => 'creme brulee'
Return the substring denoted by n positive left-most characters
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);
Get string length.
Strings\length('rod'); // 3
Strings\length('marçal'); // 7
Strings\length('marçal', true); // 6
Returns an array with the lines. Cross-platform compatible
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
Strings\lowerCaseFirst('HelloWorld'); // => 'helloWorld
Pads the string in the center with specified character. char may be a string or a number, defaults is a space
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
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
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)
Reverses a string
Strings\reverse('hello world'); // => dlrow olleh
Return the substring denoted by n positive right-most characters
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)
Converts the text into a valid url slug. Removes accents from Latin characters
Strings\slugify('Global Thermonuclear Warfare'); // => 'global-thermonuclear-warfare'
Strings\slugify('Crème brûlée'); // => 'creme-brulee'
Check if string starts with substring
Strings\startsWith("AN is a software engineer", "AN"); // => true
Strings\startsWith('wants to change the world', "politicians"); // => false
Returns a new string with all occurrences of [string1],[string2],... removed.
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?'
Strip all of the punctuation
Strings\stripPunctuation('My, st[ring] *full* of %punct)'); // => 'My string full of punct'
Returns a case swapped version of the string
Strings\swapCase('RoD eLIas'); // rOd EliAS
Repeat the string n times
Strings\times(' ', 3); // => ' '
Strings\times('*', 3); // => '***'
Creates a title version of the string. Capitalizes all the words and replaces some characters in the string to
Strings\titleize('hello world'); // => 'Hello World'
Join an array into a human readable sentence
Strings\toSentence(["A", "B", "C"]); // => "A, B and C";
Strings\toSentence(["A", "B", "C"], ", ", " ir "); // => "A, B ir C";
The same as string_to_sentence, but adjusts delimeters to use Serial comma)
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;
Strings\toLower('ROD ELIAS'); // rod elias
Makes a string uppercase;
Strings\toUpper('rod elias'); // ROD ELIAS
Truncate string accounting for word placement and character count
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'
Converts hyphens and camel casing to underscores
Strings\underscore('dataRate'); // => 'data_rate'
Strings\underscore('CarSpeed'); // => 'car_speed'
Strings\underscore('yesWeCan'); // => 'yes_we_can'
Converts string first char to uppercase
Strings\upperCaseFirst('helloWorld'); // => 'HelloWorld
Invoke a method if condition is true
Invoke\ifCondition(function () { echo 'Hello World'; }, [], Funct\notEmpty('Hello?')); // => Hello World
Invoke a method if value isset
Invoke\ifIsset(function () { echo 'Hello World'; }, ['Hello' = > 1000], 'Hello'); // => Hello World
Invoke a method if value is not empty
Invoke\ifNotEmpty(function () { echo 'Hello World'; }, 'Hello'); // => Hello World
Creates array from objects using valueMethod as value and with/without keyMethod as key
Object\toArray($objects, 'getValue', 'getkey'); // => ['key' => 'value']
Assign value to object from array if key exists
$array = ['bar' => 'foobar'];
Object\assignIfIsset($object, 'foo', $array, 'bar'); // => $object->foo = 'foobar'
$ composer test
Please see CONTRIBUTING and CONDUCT for details.
Please see License File for more information.