I want to create a callback function to remove from a numeric array the given values.
Given this array: [ 0, 0, 0, 0, 1, 0, 3, 4, 5, 2, 0, ];
I want to create a callable function to be passed to array_filter
that will return this array: [1, 0, 3, 4, 5, 2, 0, ];
. I have seen in this answer the use of array_filter: Deleting an element from an array in PHP but is not exactly what I need because this option will remove all the 0s from the array and I need to keep the ones that are not trailing.
I have created this function that cycles the array and returns the expected array, but I want to use something more efficient:
function removeTrailing( int $array_values[], $to_remove = 0 )
{
$is_trailing = true;
$result = [];
foreach( $array_values as $value ) {
if( ( $value == $to_remove ) && ( $is_trailing == true ) ) {
// Do nothing because it is a trailing $to_remove
}
else {
$result[] = $value;
$is_trailing = false;
}
}
return $result;
}