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
)
)
3 Answers 3
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';
}));
Comments
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++;
}
Comments
Your filter needs a little work:
array_filter($data, function ($datum) { return $datum['paymentType'] == 'paypal'; })
array_filtertakes 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 usearray_filter.