Strings\countChars()

reducer returns Closure pure
int → (string → int[] | string)
At a glance — Bind a mode flag; the returned Closure wraps 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): Closure

Returned Closure

When 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): string

You can use the following constants to define the mode of the function:

Constants added in V3.0.0

Examples

Partial Application

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']

Curried

This can be called inline using currying.

echo Strings\countChars(CHAR_COUNT_STRING_UNIQUE)('AABBBBBBBCCC'); // [ABC]

Inlined with Higher Order Function

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]

Details

Strings Functions

Releated String analysis Functions