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()).

'lorem impsum',
['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:

'm' => 'Mark',
'r' => 'Robert',
'l' => 'lorem impsum',
'j' => 'Jane',
's' => 'FooBar123'
['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:

'Mark' => 'm',
'Robert' => 'r',
'lorem impsum' => 'l',
'Jane' => 'j',
'FooBar123' => 'f'
['Mark' => 'm', 'Robert' => 'r', 'Jane' => 'j']
Last updated on