Search code examples
phparraysnullconditional-statementssubtraction

How to conditionally perform subtraction between corresponding elements from two arrays?


I am trying to subtract the values from two arrays. I have also tried with an if condition, null value, foreach and a lot other methods like array_filter, but I failed.

$exit_price contains:

array (
    0 => 2205,
    1 => 6680,
    2 => 50351,
    3 => 100,
    4 => 100,
    5 => 1200,
    6 => 900,
    7 => 234,
    8 => 2342,
    9 => 45654
)

$stoploss contains:

array (
    0 => null,
    1 => null,
    2 => null,
    3 => null,
    4 => null,
    5 => null,
    6 => 145300,
    7 => null,
    8 => null,
    9 => 12222
)

How can I get the following result by subtracting $stoploss from $exit_price while omitting results where the $stoploss value is null?

Expected result:

array (
    6 => -144400,
    9 => 33432
)

Solution

  • You can simply iterate the first array and check the corresponding element in the second for a null value. If the value is not null, perform the subtraction and store the difference in a new "results" array using the current key.

    $results = [];
    
    foreach ($stoploss as $key => $value) {
        if (!is_null($value)) {
            $results[$key] = $exit_price[$key] - $value;
        }
    }