0

i have this below array:

PHP

$arr=array('A','A','B','C');

i want to check value and if values are duplicate must be alert error

PHP

$chk=array_count_values($array);
if ( $chk[0] < 1 || $chk[2] < 1 || $chk[3] < 1  || $chk[4] < 1 )
    echo 'array must be uniq';
Tony Stark
  • 7,934
  • 8
  • 43
  • 63
  • 1
    Check the first "Related" link to the right: http://stackoverflow.com/questions/1170807/how-to-detect-duplicate-values-in-php-array?rq=1 .. If one of the values (see the accepted answer) > 0.. you have a duplicate.. – Damien Overeem Mar 05 '13 at 08:34

5 Answers5

12

Using array_unique(), this can be easily refactored into a new function:

function array_is_unique($array) {
   return array_unique($array) == $array;
}

Example:

$array = array("a", "a", "b", "c");
echo array_is_unique($array) ? "unique" : "non-unique"; //"non-unique"
Jacob Relkin
  • 156,685
  • 31
  • 339
  • 316
1

Try this :

$arr  =   array('A','A','B','C');
if(count($arr) != count(array_unique($arr))){
  echo "array must be uniq";
}
Prasanth Bendra
  • 29,105
  • 8
  • 50
  • 70
0

Just try with:

if ( count($arr) != count(array_unique($arr)) ) {
  echo 'array must be uniq';
}
hsz
  • 143,040
  • 58
  • 252
  • 308
0

You could walk thhrough it with a foreach loop and then use the strpos function to see if a string contains duplicates

0

From Php documentation

array array_unique ( array $array [, int $sort_flags = SORT_STRING ] )

Takes an input array and returns a new array without duplicate values.

Community
  • 1
  • 1
Bigood
  • 10,398
  • 3
  • 42
  • 69