Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect duplicate values in PHP array?

Tags:

arrays

php

I am working with a one dimensional array in PHP. I would like to detect the presence of duplicate values, then count the number of duplicate values and out put the results. For example, given the following array:

$array = array('apple', 'orange', 'pear', 'banana', 'apple',    'pear', 'kiwi', 'kiwi', 'kiwi'); 

I would like to print:

apple (2) orange pear (2) banana kiwi (3) 

Any advice on how to approach this problem?

Thanks.

Mike

like image 941
mikey_w Avatar asked Jul 23 '09 10:07

mikey_w


People also ask

How do you find duplicate values in an array?

function checkIfArrayIsUnique(myArray) { for (var i = 0; i < myArray. length; i++) { for (var j = 0; j < myArray. length; j++) { if (i != j) { if (myArray[i] == myArray[j]) { return true; // means there are duplicate values } } } } return false; // means there are no duplicate values. }

Which function remove duplicate values from an array?

Answer: Use the indexOf() Method You can use the indexOf() method in conjugation with the push() remove the duplicate values from an array or get all unique values from an array in JavaScript.

What is Array_map function in PHP?

The array_map() is an inbuilt function in PHP and it helps to modify all elements one or more arrays according to some user-defined condition in an easy manner. It basically, sends each of the elements of an array to a user-defined function and returns an array with new values as modified by that function.


1 Answers

You can use array_count_values function

$array = array('apple', 'orange', 'pear', 'banana', 'apple', 'pear', 'kiwi', 'kiwi', 'kiwi');  print_r(array_count_values($array)); 

will output

Array (    [apple] => 2    [orange] => 1    [pear] => 2    etc... ) 
like image 168
Silfverstrom Avatar answered Sep 22 '22 14:09

Silfverstrom