I want to subtract one array from another .
for example I have 2 arrays.
Array
(
[0] => 251
[1] => 251
[2] => 130
)
Array
(
[0] => 13
[1] => 13
[2] => 50
)
The resulting array has to be
Array
(
[0] => 238
[1] => 238
[2] => 80
)
Any sort of help on this is appreciated .
Description. C = A - B subtracts array B from array A by subtracting corresponding elements. The sizes of A and B must be the same or be compatible. If the sizes of A and B are compatible, then the two arrays implicitly expand to match each other.
subtract() function is used when we want to compute the difference of two array.It returns the difference of arr1 and arr2, element-wise. Parameters : arr1 : [array_like or scalar]1st Input array.
In this program, we need to get the result of subtraction of two matrices. Subtraction of two matrices can be performed by looping through the first and second matrix. Calculating the difference between their corresponding elements and store the result in the third matrix.
If you are mentioning the subtraction of the elements that have the same indexes, you have to make sure that the array's size is equal. Then iterate through both arrays and subtract one to another using loop. The thing you want to achieve results in undefined behavior.
Try this :
$array1 = array(251, 251, 130);
$array2 = array( 13, 13, 50);
$res = array();
for($i=0;$i<count($array1);$i++){
$res[$i] = $array1[$i]-$array2[$i];
}
echo "<pre>";
print_r($res);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With