Zils Zils - 1 year ago 155
PHP Question

Using array_sum() filtered from another array

$type=array("debit", "credit", "credit", "credit", "debit");


how to
values or all

expected result:
debit= 20+60 = 80
credit=30+40+50 =120

I've tried to filter it then use array_sum but not working.

function filterDebit($finddebit){
return ($finddebit == "debit");
$finaldebit = array_filter($type, 'filterDebit');
echo array_sum($finaldebit);

Answer Source

You can't quite get the sum that way because you aren't actually doing anything with the array of amounts, but you've already gotten pretty close.

You can use array_intersect_key to find the entries in $amount that match the keys in your filtered $types array.

echo array_sum(array_intersect_key($amount, $finaldebit));

If it's possible, I think it would be better to address this problem at some earlier point, so the two sets of associated values don't end up in separate arrays like this, especially if the two arrays came from a database, which would be able to handle this filtering/aggregation more efficiently, but since I don't know the source of the arrays, I don't have a suggestion for that.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download