Skip to main content

Filtering an array

Documentation for version: 0.41.2

Method Pattern.filter() returns a new, sequential array containing only values which match the given pattern.

/*
* Instantiate pattern
*/
$pattern = Pattern::of('[A-Z][a-z]+$');
/*
* Populate the array
*/
$array = [
'Mark',
'Robert',
'lorem impsum',
'Jane',
'FooBar123'
];
/*
* Filter the array by matching the pattern
*/
$pattern->filter($array);
['Mark', 'Robert', 'Jane']

More precisely, Pattern.filter() returns [0 => 'Mark', 1 => 'Robert', 2 => 'Jane'], even though the original key for 'Jane' was 3.

Only values of type string are allowed in the array as the argument for Pattern.filter(). Passing an array with a value of any other type than string issues \InvalidArgumentException.

The resulting array contains subjects for which calling Pattern.test() on the same $pattern returns true. The elements which are no longer present in the resulting array, are subjects for which calling Pattern.test() returns false.

Inversely filtering an array#

Method Pattern.reject() returns a new, sequential array containing only values which do not match the given pattern.

/*
* Instantiate pattern
*/
$pattern = Pattern::of('[A-Za-z]+$');
/*
* Populate the array
*/
$array = [
'Mark',
'Robert',
'123',
'Jane',
'4567'
];
/*
* Inversely filter the array by matching the pattern
*/
$pattern->reject($array);

Only values of type string are allowed in the array as the argument for Pattern.reject(). Passing an array with a value of any other type than string issues \InvalidArgumentException.

Stable filtering#

Pattern.filter() and Pattern.reject() can be interpreted as what's called a "stable filtering". What it means, is that if the input array contains multiple occurrences of the same string subject, then exactly as many subject string is returned.

/*
* Instantiate pattern
*/
$pattern = Pattern::of('\w+');
/*
* Populate the array
*/
$array = ['one', 'one', 'two'];
/*
* Filter the array
*/
$filtered = $pattern->filter($array);

The array $filtered is [0 => 'one', 1 => 'one'].

Another characteristic of "stable filtering" is that the order items in the input array doesn't change after the filtering. More precisely - for any two items in the array, one item A preceding the other item B; then item A also precedes item B in the filtered array.

Last updated on