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