Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subtracting one array from another

Tags:

arrays

php

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 .

like image 921
Justin Avatar asked Mar 06 '13 10:03

Justin


People also ask

Can you subtract two arrays?

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.

How do you subtract one array from another in python?

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.

Can we subtract two arrays in Java?

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.

Can we subtract two arrays in C++?

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.


1 Answers

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);
like image 103
Prasanth Bendra Avatar answered Sep 20 '22 18:09

Prasanth Bendra