Re: Number of duplicates in an array?
| From: | David Otton | Date: | Mon, 18 Aug 2008 14:40:08 +0000 |
| Subject: | Re: Number of duplicates in an array? | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-278282@lists.php.net to get a copy of this message | ||
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/