PHP | Ds\Vector filter() Function

The Ds\Vector::filter() function is used to filter out the only elements which satisfy the condition defined in the callback function. After doing a filter on the vector, it will eliminate the elements which do not satisfy the condition mentioned in the function.
Syntax:
Ds\Vector public Ds\Vector::filter( $callback )
Parameters: This function accepts single parameter $callback which returns true if the element in the vector is to be included, else return false.
Return Value: This function returns the vector with all the elements which are filtered according to the callable function.
Below programs illustrate the Ds\Vector::filter() function in PHP:
Program 1:
<?php   // Create new vector element $vector = new \Ds\Vector([1, 2, 3, 4, 5]);   echo "Original Vector elements\n";   // Display the vector element var_dump($vector);   echo("\nElements greater than or equal to 4\n");   // Filter the vector element var_dump($vector->filter(function($value) {     return $value >= 4; }));   ?> |
Output:
Original Vector elements
object(Ds\Vector)#1 (5) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
[3]=>
int(4)
[4]=>
int(5)
}
Elements greater than or equal to 4
object(Ds\Vector)#3 (2) {
[0]=>
int(4)
[1]=>
int(5)
}
Program 2:
<?php   // Create new vector element $vector = new \Ds\Vector([1, 2, 3, 4, 5]);   echo "Original Vector elements\n";   // Display the vector element var_dump($vector);   echo("\nOdd elements\n");   // Use filter() function to filter // the vector element var_dump($vector->filter(function($value) {     return $value % 2 == 1; }));   ?> |
Output:
Original Vector elements
object(Ds\Vector)#1 (5) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
[3]=>
int(4)
[4]=>
int(5)
}
Odd elements
object(Ds\Vector)#3 (3) {
[0]=>
int(1)
[1]=>
int(3)
[2]=>
int(5)
}
Reference: http://php.net/manual/en/ds-vector.filter.php
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, zambiatek Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!



