Khoa Trumcuoi
Khoa Trumcuoi

Reputation: 33

php compare 2 array and manipulation increase value

I have 2 array

a=array(a=>1,b=>2,c=>2,d=>2,e=>2,f=>2)

and

b=array(a,b,d)

I want to make function compare_plus(array a, array b) like if array a have key== array b val then in increase value of array a at this key by 1.

Example with above array a and b:

c=compare_plus(a,b) =>> c=(a=>2,b=>3,c=>2,d=>3,f=>2)

Upvotes: 0

Views: 95

Answers (2)

DACrosby
DACrosby

Reputation: 11470

If you want to add only to existing keys and not create additional ones, you'll need something like this:

$a = array("a" => 1, "b" => 2, "c" => 2, "d" => 2, "e" => 2, "f" => 2);
$b = array("a", "b", "d", "g", "apple");

$c = compare_plus($a, $b);
print_r($c);

function compare_plus($arr, $plusarr){
    foreach($plusarr as $key)
        if (array_key_exists($key, $arr))
            $arr[$key]++;
    return $arr;
}

/* // Output:
Array
(
    [a] => 2
    [b] => 3
    [c] => 2
    [d] => 3
    [e] => 2
    [f] => 2
)
*/

To add the additional keys from $b to $c, simply remove if (array_key_exists($key, $arr)).

http://codepad.org/aquc5DKA

Upvotes: 1

Paul
Paul

Reputation: 141937

$a = array('a' => 1, 'b' => 2, 'c' => 2, 'd' => 2, 'e' => 2, 'f' => 2);
$b = array('a', 'b', 'd');

$c = compare_plus($a, $b);
print_r($c);

function compare_plus($arr, $plusarr){
    foreach($plusarr as $key)
        $arr[$key]++;
    return $arr;
}

Codepad Demo

Upvotes: 1

Related Questions