0

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.

1
  • array_value_count(array_column('coupon_type')); Commented Jul 30, 2016 at 9:57

2 Answers 2

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

@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.
0

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++;
       }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.