Bluehost.com Web Hosting $6.95

Re: [PHP] Number of duplicates in an array?

This is a discussion on Re: [PHP] Number of duplicates in an array? within the PHP General forums, part of the PHP Programming Forums category; 2008/8/18 tedd <tedd@sperling.com>: > Anyone have a cool method of finding duplicate items in ...


Go Back   Usenet Forums > PHP Programming Forums > PHP General

FAQ Members List Calendar Search Today's Posts Mark Forums Read
  #1 (permalink)  
Old 08-18-2008
David Otton
 
Posts: n/a
Default Re: [PHP] Number of duplicates in an array?

2008/8/18 tedd <tedd@sperling.com>:

> Anyone have a cool method of finding duplicate items in an array and the
> number of times they appear?
>
> I'm doing it in a way that is probably less than optimum. I want to see how
> you guys solve it.


Hmm. Assuming the following inputs and outputs:

$input_array = array( 'one', 'two', 'three', 'one', 'two', 'one' );
$output_array = array( 'one' => 3, 'two' => 2, 'three' => 1 );

$input_array = array( 'one', 'two', 'three', 'one', 'two', 'one' );
$output_array = array();
foreach( $input_array as $input )
{
if ( !isset( $output_array[$input] ) )
{
$output_array[$input] = 0;
}
$output_array[$input]++;
}

Untested code.

From a CompSci PoV, input_array is a list while output_array would be
better implemented as a binary tree (with the normal caveats about
tree balancing). But given that we're working in PHP and your data
sets probably aren't that large, this is the "good enough" solution.

--

http://www.otton.org/
Reply With Quote
Reply
Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are Off
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On




All times are GMT +1. The time now is 02:38 AM.


Powered by vBulletin® Version 3.7.3
Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
Content Relevant URLs by vBSEO 3.0.0