Counting PHP Array Repetitions

Sat Oct 17 04:07:54 2009

The ability to check an array in php and see if the items it contains reoccur somewhere else inside the array is something that comes in handy once in a while. If for example, you have a list of dates and you wanted to count how many times the same date reoccurs in the array and display the results, this is what you would do.

<?php
 $arrayToCount = array("1981","1973","2010","1973","1981","1973");

 foreach( $arrayToCount as $val ) {
   if ( array_key_exists( $val, $arrayCounter) ) { 
      $arrayCounter[$val]++; 
   }
   else { 
      $arrayCounter[$val] = 1;
   }
 }
	
 while( $element = each( $arrayCounter ) ){
 echo $element[ 'key' ].' ('.$element[ 'value' ].')';
}
?>

As is, the results of this would look like this

1981 (2)
1973 (3)
2010 (1)

Here's what's happening. Obviously, we have an array containing dates that we want to count shown on line 1. We use a foreach loop to run the contents of the loop for however many dates are contained inside the array. An if/else statement is used on line 4 through 9, which uses the PHP function array_key_exists()(line 4.), which checks to see if $val (the date being checked) matches a value previously looped through. If this function returns true the value inside $arrayCounter gets pushed up by 1 or ++ each time (see line 5). If the array_key_exists() on line 4 returns false, or in other words, no match is found, then the value 1 gets added to a new place in the $arrayCounter array. We then use a while statement to display each of the dates and their count values stored inside the associative array $arrayCounter(lines 12 ~ 14)

And that's about it. If you are new to PHP, I would recommend drilling this kinds of routine into your head and you'll get your head around it before you know it.


← back

Most recent posts

  1. Convert Font Suitcase to TTF in 3 Easy Steps
  2. Rain or Shine - Weather Forecast Available Now!
  3. Getting around Apple's silly rules for iOS 10
  4. Localising App Names for iOS and Android
  5. Today - Powerful To-Do App Now Available on iOS & Android

Search site:

Apps by Ubacoda.com

Click the app icons to see more info


Archives

Categories