I have the following array that I want to count the element of "PaymentType" == paypal. I am using this method $totalcount = count(array_filter((array) $data[0], 'paypal')); but get the warning "'paypal', should be a valid callback" Appreciate any response to help me get going in the right direction.

Array
(
[0] => Array
    (
        [TransactionDate] => 0000-00-00 00:00:00
        [TotalAmount] => 0.00
        [PayPalFee] => 2.48
        [PayPalTransactionID] => 92
        [PaymentType] => paypal
    )

[1] => Array
    (
        [TransactionDate] => 0000-00-00 00:00:00
        [TotalAmount] => 0.00
        [PayPalFee] => 2.48
        [PayPalTransactionID] => 3
        [PaymentType] => paypal
    )

[2] => Array
    (
        [TransactionDate] => 2011-05-16 11:15:02
        [TotalAmount] => 75.00
        [PayPalFee] => 2.48
        [PayPalTransactionID] => 2
        [PaymentType] => paypal
    )
)
link|improve this question

2  
array_filter takes a callback as second argument, as described in the documentation: php.net/manual/en/function.array-filter.php. There you will also find examples on how to use array_filter. – Felix Kling Jan 3 at 14:44
feedback

3 Answers

up vote 0 down vote accepted

array_filter() is supposed to return a filtered array (and also needs a callback function to work, not a search value) - you don't need to do that. Here's a solution that really only counts the matches:

$totalcount = 0;
for ($i = 0, $c = count($data[0]); $i < $c; $i++)
{
    if ($data[0][$i]['PaymentType'] === 'paypal')
        $totalcount++;
}
link|improve this answer
feedback

array_filter() requires a callback for the 2nd argument. You have to write a custom function to filter out only the results you want, like below:

$totalcount = count(array_filter($data, function($arr)
{
    return $arr['PaymentType'] == 'paypal';
}));
link|improve this answer
feedback

Your filter needs a little work:

array_filter($data, function ($datum) { return $datum['paymentType'] == 'paypal'; })
link|improve this answer
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.