Skip to content

Instantly share code, notes, and snippets.

@rifki
Created September 30, 2015 17:52
Show Gist options
  • Save rifki/15146d86a46fe9783ebe to your computer and use it in GitHub Desktop.
Save rifki/15146d86a46fe9783ebe to your computer and use it in GitHub Desktop.
check is duplicate value in array - php
<?php
//check duplicate entry
$arr = [1,2,3,3,3,4,4,5,6,7,8,9,10,10,10,10,10,20,20];
// solution 1
function has_duplicate1($array) {
$dupl = [];
$space = php_sapi_name() == 'cli' ? "\n" : "<br>";
foreach(array_count_values($array) as $value => $count) {
if ($count > 1) {
$dupl[$count] = $value;
printf("duplicate value = [%s] AND count = [%s] %s", $dupl[$count], $count, $space);
}
}
}
// solution 2
function has_duplicate2($array) {
$space = php_sapi_name() == 'cli' ? "\n" : "<br>";
$dupl = [];
foreach ($array as $value) {
if (++$dupl[$value] > 1) {
printf("duplicate value = [%s] %s", $value, $space);
}
}
}
// run
has_duplicate1($arr);
echo "<hr>";
has_duplicate2($arr);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment