2

I have an array contacting following words

(“hello”, “apple”, “hello”, “hello”, “apple”, “orange”, “cake”)

Result here should be 5

Can you please tell me if there is a library function in PHP that I can use to count how many duplicate words are present in my array? Any help would be greatly appreciated.

1
  • Thank you all for the detaied information. they all were very helpful Commented Jun 19, 2013 at 14:25

5 Answers 5

5

You can combine array_unique() with count():

$number_of_duplicates = count($words) - count(array_unique($words));

Note: PHP has over a hundred Array Functions. Learning them will make you a better PHP Developer.

Sign up to request clarification or add additional context in comments.

Comments

3

Check array_count_values https://www.php.net/manual/en/function.array-count-values.php

<?php
var_dump(array_count_values($words));

Output:
Array(
    [hello] => 3,
    [apple] => 2,
    [orange] => 1,
    [cake] => 1
)

1 Comment

While this doesn't answer the question directly, it is an alternative approach.
0
$array = array(“hello”, “apple”, “hello”, “hello”, “apple”, “orange”, “cake”);
$unique_elements = array_unique($array);
$totalUniqueElements = count($unique_elements); 
echo $totalUniqueElements; 
//Output 5

Hope this will help you.

Comments

0

Try like this

$count1 = count($array);
$count2 = count(array_unique($array));
echo $count1 - $count2;

Comments

0

You could do this:

$org = count($array);
$unique = count(array_unique($array));
$duplicates = $org - $unique

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.