Skip to content

Instantly share code, notes, and snippets.

@farhadhp
Created April 19, 2017 16:43
Show Gist options
  • Save farhadhp/75b4244a5f8535800c3112cd01d51dbd to your computer and use it in GitHub Desktop.
Save farhadhp/75b4244a5f8535800c3112cd01d51dbd to your computer and use it in GitHub Desktop.
has_duplicated_array : An simple function to check if given array contains duplicated values
<?php
/*
* Author : Farhad Hassan Pour (https://farhadhp.github.io/)
*/
function has_duplicated_array($arr) {
$count_value = array_count_values($arr);
rsort($count_value);
return $count_value[0] > 1;
}
/*
* Example
*/
$my_array = array('a','b','c','d','e','b','b','d','c','e','e','e','e');
if(has_duplicated_array($my_array)) {
echo 'duplicat';
}else{
echo 'not duplicat!';
}
// output : duplicat
@xmgr
Copy link

xmgr commented Apr 19, 2017

And a bit shorter:

<?php
	
	$arr = [ 1, 2, 3, 3 ];
	
	echo "Array does " . ( hasDuplicates($arr) ? '' : 'not ' ) . "have duplicates.";
	
	/**
	 * Checks if array has duplicate values in it
	 *
	 * @param array $value The array
	 *
	 * @return bool
	 */
	function hasDuplicates($value) {
		return count(array_count_values($value)) != count($value);
	}

?>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment