I have an array and I want to subtract a number "n" starting from the last index, some examples:
[1,2,3,4] - 2 = [1,2,3,2]
[1,2,3,4,0,0] - 3 = [1,2,3,1,0,0]
[1,2,3,4,0] - 6 = [1,2,1,0,0]
The subtracting number will never be greater than the sum of array values.
Currently I'm using a solution for fixed array sizes with a trivial loop and subtraction. How would I approach this for a dynamic size? What PHP methods will make this easier?
I've prepared a small sample code which should work:
$arr1 = array( 1,2,3,4); //-2
$arr2 = array( 1,2,3,4,0,0); //-3
$arr3 = array( 1,2,3,4,0,); //-6
array_subtract( $arr1, 2 );
array_subtract( $arr2, 3 );
array_subtract( $arr3, 6 );
print_r($arr1);
print_r($arr2);
print_r($arr3);
//heres a handy function which requires the array and the subtraction value as input
function array_subtract( &$array, $sub ) {
$size = sizeof( $array ) - 1;
for( $i = $size; $i >= 0; $i-- ) :
if ($sub > 0 ) :
if ( $array[$i] > $sub ) :
$array[$i] -= $sub;
$sub = 0;
else :
$sub -= $array[$i];
$array[$i] -= $array[$i];
endif;
else :
break;
endif;
endfor;
}
The print_r
output looks like
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 2
)
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 1
[4] => 0
[5] => 0
)
Array
(
[0] => 1
[1] => 2
[2] => 1
[3] => 0
[4] => 0
)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments