Pairwise subtraction of two arrays

There are two arrays:

 $arr1 = array(1,2,3);
 $arr2 = array(0,0,1);

I need to make pairwise subtraction of these two arrays. The result for arr1 - arr2 should be:

$arr3 = array(1,2,2).

Do I need to use FOR loop to to this or is there any quicker way?

Answers


How about this function?

function array_sub_values($arr1, $arr2)
{
    $result = array();
    foreach ($arr1 as $k => $val)
        $result[] = $val - $arr2[$k];
    return $result;
}

So you can do:

$arr1 = array(1, 2, 3);
$arr2 = array(0, 0, 1);

$arr3 = array_sub_values($arr1, $arr2);

In addition to the other answers, you could also use array_map()

function sub($x, $y){
    return $x - $y;
}

$arr3 = array_map('sub', $arr1, $arr2);

Need Your Help

Play framework template parameter - pass a subclass

playframework playframework-2.1

I have a view template that accepts the following parameter:

Is there a way to load a particular part of a page then later load another part of the page without using JQuery and Ajax?

jquery ajax web

For this project, I have to have it so that the page loads while making queries the database, but even if the query hasn't finished loading, I want the page to show up with and wait for the query t...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.