Search code examples
phparraysmultidimensional-arraysumfiltering

Sum column values but only if specific key exists in same row


I need to sum the price values of all rows where the optional check element exists.

Sample data:

[
    6254 => [
        'check' => 'on',
        'quantity' => 2,
        'name' => 'Testing product_special One Size',
        'total' => 15.9,
        'price' => 33.0000,
        'totalken' => 33075.9,
    ],
    6255 => [
        'quantity' => 1,
        'name' => 'Testing card',
        'total' => 113.85,
        'price' => 33.0000,
        'totalken' => 16537.95,
    ],
    6256 => [
        'check' => 'on',
        'quantity' => 1,
        'name' => 'Testing food',
        'total' => 113.85,
        'price' => 33.0000,
        'totalken' => 16537.95,
    ],
]

I tried array_sum(array_column($value, 'price')) but this sums all price values regardless of the check value.

Expected result: 66


Solution

  • I would use array_reduce in this case.

    array_reduce loops through the array and uses a callback function to reduce array to a single value.

    <?php
    
    $totalPrice = array_reduce($myArray, function ($accumulator, $item) {
        // I'm checking 'check' key only here, you can test for 'on' value if needed
        if (isset($item['check'])) { 
            $accumulator += $item['price'];
        }
        return $accumulator;
    });