What is the DS\Vector filter() method in PHP?

The filter() method of the DS\Vector class in PHP eliminates the values that fail to satisfy the condition defined in a provided callback function from a vector.

The process is illustrated below:

The prototype of the filter() method is shown below:

Ds\Vector public Ds\Vector::filter( $callback )

Parameters

The filter() method accepts a single optional parameter: a callback function that defines the condition based on which values are eliminated from the vector.

Return value

The filter() method returns a new vector that contains all the values of the original vector for which the callback function returns true.

If the callback function is not provided as a parameter, the filter() method only retains the values evaluated as true.

Note: You can check the following link to learn how values are evaluated as Boolean in PHP.

Example

The code below shows how the filter() method works in PHP:

<?php
// initialize vectors
$firstVector = new \Ds\Vector([1, 5, 8, 10, 15]);
$secondVector = new \Ds\Vector([0, 'abc', 10, true, false]);
// filter out all values not divisible by 5
$filterFirst = $firstVector->filter(function($value){
return $value % 5 == 0;
});
// filter without callback
$filterSecond = $secondVector->filter();
// print filtered vectors
print_r($filterFirst);
print_r($filterSecond);
?>

The above code produces the following output:

Ds\Vector Object
(
[0] => 5
[1] => 10
[2] => 15
)
Ds\Vector Object
(
[0] => abc
[1] => 10
[2] => 1
)

Note: To run this program, you need to install Data Structures for PHP on your local machine.

Explanation

First, two vectors are initialized: firstVector and secondVector.

The filter() method in line 88 proceeds to filter out values from firstVector. The callback function provided to this filter() method returns true if a value is divisible by 55. Therefore, the filter() method returns a new vector that contains only the values of firstVector that are divisible by 55.

The filter() method in line 1313 filters out values from secondVector. Since no callback function is provided to the filter() method, it eliminates all the values of secondVector that do not evaluate to true, i.e., 00 and false.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved