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
  • 8,064
  • 8
  • 44
  • 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

13

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
  • 161,348
  • 33
  • 346
  • 320
1

Try this :

$arr  =   array('A','A','B','C');
if(count($arr) != count(array_unique($arr))){
  echo "array must be uniq";
}
Prasanth Bendra
  • 31,145
  • 9
  • 53
  • 73
0

Just try with:

if ( count($arr) != count(array_unique($arr)) ) {
  echo 'array must be uniq';
}
hsz
  • 148,279
  • 62
  • 259
  • 315
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
Maen
  • 10,603
  • 3
  • 45
  • 71