count_chars(). Return shape (array vs. string) depends on the flag.
Allows you to create a function which can be used to split into groups of specified chunk lengths. These can either be used as part of a Higher Order Function such as array_map() or as part of a compiled/pipe function.
/**
* @param int $mode See details below.
* @return Closure(string):(int[]|string)
*/
Strings\countChars(int $mode = CHAR_COUNT_ARRAY_KEYED): ClosureWhen Strings\countChars() is called, it returns the following Closure which can be used like a regular function.
/**
* @param string $string The string to have its char counted.
* @return int[]|string
* @psalm-pure
*/
$function(string $string): stringYou can use the following constants to define the mode of the function:
CHAR_COUNT_ARRAY :: an array with the byte-value as key and the frequency of every byte as value.CHAR_COUNT_ARRAY_UNIQUE :: same as CHAR_COUNT_ARRAY_KEYED but only byte-values with a frequency greater than zero are listed.CHAR_COUNT_ARRAY_UNUSED :: same as CHAR_COUNT_ARRAY_KEYED but only byte-values with a frequency equal to zero are listed.CHAR_COUNT_STRING_UNIQUE :: a string containing all unique characters is returned.CHAR_COUNT_STRING_UNUSED :: a string containing all not used characters is returned.Constants added in V3.0.0
This can be used to create a simple closure which can be used as a regular function.
// Create a closure which will count chars in a string as an array.
$countToArray = Strings\countChars(CHAR_COUNT_ARRAY); // $mode = 0
// Create a closure which will count chars in a string as a string.
$countToString = Strings\countChars(CHAR_COUNT_STRING_UNIQUE); // $mode = 3
// Called as a function.
print_r( countToArray('AABBCC')); // [65 => 2, 66 => 2, 67 => 2]
echo countToString('AABBCC'); // ABC
// Used in a higher order function.
$array = array_map( $countToString, ['This is a string', 'Different words']);
print_r($array); // [' Taghinrst', ' Ddefinorstw']This can be called inline using currying.
echo Strings\countChars(CHAR_COUNT_STRING_UNIQUE)('AABBBBBBBCCC'); // [ABC]If you are not planning on reusing the Closure created, you can just call it inline with a higher order function as its callable.
$array = array_map( Strings\countChars(CHAR_COUNT_STRING_UNIQUE), ['This is a string', 'Different words']);
print_r($array); // [' Taghinrst', ' Ddefinorstw']
// Can be piped with char() to cast BYTE to string.
$count = GeneralFunctions\pipe('AABBCC', Strings\countChars(CHAR_COUNT_ARRAY), 'char');
print_r($count); // [A => 2, B => 2, C => 2]