Filter an array

Filtering an array, returns a new array with only the values that match the pattern.

Available methods for pattern()->forArray() are:

Filter a regular array#

Method filter() filters an array and returns values re-indexed to match the removed elements (unlike array_filter()).

pattern('[A-Z][a-z]+$')
->forArray([
'Mark',
'Robert',
'lorem impsum',
'Jane',
'FooBar123'
])
->filter();
['Mark', 'Robert', 'Jane']

More precisely it returns [0 => 'Mark', 1 => 'Robert', 2 => 'Jane'], even though original key for 'Jane' was 3.

Filter an associative array#

Method filterAssoc() works similarly to filter(), but it preserves the array keys:

pattern('[A-Z][a-z]+$')
->forArray([
'm' => 'Mark',
'r' => 'Robert',
'l' => 'lorem impsum',
'j' => 'Jane',
's' => 'FooBar123'
])
->filterAssoc();
['m' => 'Mark', 'r' => 'Robert', 'j' => 'Jane']

Filter by keys#

With filter() and filterAssoc(), only array values are being used to filter the array. With filterByKeys(), it's the array keys that are used to filter the array. The corresponding values (which can be of type mixed) are returned unchanged:

pattern('[A-Z][a-z]+$')
->forArray([
'Mark' => 'm',
'Robert' => 'r',
'lorem impsum' => 'l',
'Jane' => 'j',
'FooBar123' => 'f'
])
->filterByKeys();
['Mark' => 'm', 'Robert' => 'r', 'Jane' => 'j']
Last updated on