Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Hi i have a repeating dates in array values i wan to count the number of repeating dates from the array value. I tried this but am not sure to do it correctly and am getting error Undefined offset: 0

<?php $array = array('2013-11-28','2013-11-28','2013-11-28','2013-11-29','2013-11-29','2013-11-30');

$len = sizeof($array);
$len = $len-1;
$day = array();
for($i=0; $i<=$len; $i++)
{
    for($j=0; $j<=$len; $j++)
    {
        if($array[$i] == $array[$j])
        {
            if($day[0] == '')
            {
                $co = 1;
                $day[] = $co;
            }
            else {
                $day[$i] = $co++;
            }
        }
    }
    echo 'day'.$i.' '.$day[$i].' ';
}
?>

From the date values i should get 3 for 2013-11-28, 2 for 2013-11-29 and 1 for 2013-11-30 as you can see 2013-11-28 is presented 3 times , 2013-11-29 is presented 2 times and 2013-11-30 is presented one time.

I can understand that i am wrongly calculating because in the second loop i am again starting from first index so increasing the count.

I want to know the count of same dates. How to do this. Any other way to count this? Any help please?

share|improve this question
    
You want to group and count? like 2013-11-28 = 3, 2013-11-29 = 2 and 2013-11-30 = 1? –  haim770 Nov 28 '13 at 8:15
    
$len = sizeof($array); use $len = count($array); –  SHIN Nov 28 '13 at 8:15
2  
@SHIN sizeof and count are equivalent. –  Barmar Nov 28 '13 at 8:16
    
The error is because of if ($day[0] == ''). You do this before you ever add anything to $day, so there's no element 0 yet. –  Barmar Nov 28 '13 at 8:17
    
yes, thanks. +1 for sizeof and count @Barmar –  sun Nov 28 '13 at 8:17
show 9 more comments

1 Answer

up vote 3 down vote accepted

Use array_count_values().

$dupesCount = array_count_values($array);

This will give you an array where the value is the key and the new value is the repetition count.

share|improve this answer
    
Thanks for easy answer. Can that be done in my loop logic too? @alex –  sun Nov 28 '13 at 8:25
    
@sun You wouldn't need to loop yourself. –  alex Nov 28 '13 at 8:27
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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