0
votes
Array
(
    [6254] => Array
        (
            [check] => on
            [quantity] => 2
            [name] => Testing product_special One Size
            [total] => 15.9
            [price] => 33.0000
            [totalken] => 33075.9
        )

    [6255] => Array
        (

            [quantity] => 1
            [name] => Testing card
            [total] => 113.85
            [price] => 33.0000
            [totalken] => 16537.95
        )
    [6256] => Array
        (
            [check] => on
            [quantity] => 1
            [name] => Testing food
            [total] => 113.85
            [price] => 33.0000
            [totalken] => 16537.95
        )

)
array_sum(array_column($value, 'price'))

using array_sum able to sum all the 'price' , but now with 1 condition:

IF in the array have "check" = on , only sum the price , if there is no "check" = on , ignore it

3

3 Answers

3
votes

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;
});
3
votes

You can simply filter the array based on condition by using array_filter() function of php.

You can see the usage of array_filter() here.

Here is my solution for you if you want to use condition.

$filteredByCheck = array_filter($value, function ($val){
           return isset($val['check']);
       });

$total = array_sum(array_column($filteredByCheck, 'price'));
2
votes

The quickest method would be just to loop over the array and maintain a sum, use ?? '' to default it to blank if not set...

$total = 0;
foreach ($value as $element )    {
    if ( ($element['check'] ?? '') == "on" )  {
        total += $element['price'];
    }
}