i have an array and i want to get the count of specific values.
The Structure is as:
Array (
[0] => Array (
[coupon_id] => 350
[coupon_title] => This is the title of coupons
[coupon_code] => ABCD
[coupon_type] => coupon
)
[1] => Array (
[coupon_id] => 350
[coupon_title] => This is the title of coupons
[coupon_code] => ABCD
[coupon_type] => no_coupon
)
)
Now i want to get the count of coupon and no_coupon
I tried by array_value_count but i am getting this can only count STRING and VALUES.
Max P.
5,6992 gold badges17 silver badges35 bronze badges
2 Answers 2
<?php
# Get the data from where you want to get the count
$array = array(
array('coupon_type' => 'coupon'),
array('coupon_type' => 'no_coupon')
);
# Count the variables
$count = array_count_values(array_column($array, 'coupon_type')));
print_r($count);
// Will show
// Array ( [coupon] => 1 [no_coupon] => 1 )
?>
Sign up to request clarification or add additional context in comments.
1 Comment
ArtisticPhoenix
@mohit - Do you want the sum, or the numbers of occurrences. I believe
array_count_values returns the number of times that key is present in the array and not the sum of it's values. Never-mind it's the number of times the value is in the array... So this should work.You can use a foreach loop for this purpose.
$count_coupon=0;
$count_no_coupon=0;
foreach ( $array as $arr )
{
if( $arr['coupon_type'] == 'coupon' )
{
$count_coupon++;
}
else if( $arr['coupon_type'] == 'no_coupon' )
{
$count_no_coupon++;
}
answered Jul 30, 2016 at 10:28
Aqueel Aboobacker VP
3661 silver badge6 bronze badges
Comments
lang-php
array_value_count(array_column('coupon_type'));