Kenziiee Flavius
Kenziiee Flavius

Reputation: 1949

PHP - Subtract value from 2 objects where key = is the same

Im not sure if ive wrote the question properly but ill elaborate more on what i need.

I have two objects which i need to change to array and they have keys 1,2,3 but they have different values i need to subtract the values from the array where the keys are the same, I hope this makes sense.

Things ive tried to far

All help appreciated any more information needed will be provided

Example Arrays:

Array 1

1 => 300.00,
2 => 300.00,
3 => 300.00

Array 2

1 => 200.00,
2 => 200.00,
3 => 200.00

Desired output

1 => 100.00,
2 => 100.00,
3 => 100.00

Upvotes: 0

Views: 1658

Answers (3)

Xzhibit
Xzhibit

Reputation: 81

For an indexed array,

function diff($arr1, $arr2){      
    $arr3=array();
    for($i=0;$i<count($arr1);$i++){
        $arr3[$i]=$arr1[$i]-$arr2[$i];
    }
    print_r($arr3);
}
$arr1=array(300,300,300);
$arr2=array(100,100,100);
diff($arr1, $arr2);
//Displays 200, 200, 200, as expected

Upvotes: 1

twigg
twigg

Reputation: 3993

The best option for this seems to be a for loop

$arr1 = [300, 300, 300];
$arr2 = [200, 200, 200];

$arr_length = sizeof($arr1) -1;

$minus_arr = [];

for($i = 0; $i <= $arr_length; $i++){
    $minus = $arr1[$i] - $arr2[$i];
    array_push($minus_arr, $minus);
}

print_r($minus_arr);

I took for granted your given arrays above, it sounds like the arrays you're using are either not the same size or have strings or nulls in them so check for an int first.

    <?php

$arr1 = [300, 300, 300];
$arr2 = [200, 200, 200];

$arr_length = sizeof($arr1) -1;

$minus_arr = [];

for($i = 0; $i <= $arr_length; $i++){
    if(is_int($arr1[$i]) && is_int($arr2[$i])){
        $minus = $arr1[$i] - $arr2[$i];
        array_push($minus_arr, $minus);
    }
}

print_r($minus_arr);

Upvotes: 1

wonyeouuu
wonyeouuu

Reputation: 189

I hope I do not misunderstand your question.

My method is iterate through 2 arrays, and whenever their keys are the same, do the operation. Here is a example:

function diff($arr1, $arr2) {
    $result = [];
    foreach($arr1 as $key1 => $value1) {
        foreach($arr2 as $key2 => $value2) {
            if ($key1 == $key2) {
                $result[$key1] = $value1 - $value2;
            }
        }
    }
    return $result;
}

I see there is Laravel in your tag, if you're using laravel, I'm sure that you can achieve this better with Collection. The document is here. It provides you a more 'OO' way (similar to javascript) you can operate arrays in php.

Upvotes: 1

Related Questions