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';
1

5 Answers 5

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"
Sign up to request clarification or add additional context in comments.

1 Comment

For PHP >= 5.1, may I suggest array type hint: function array_is_unique(array $array) { ... }
1

Try this :

$arr  =   array('A','A','B','C');
if(count($arr) != count(array_unique($arr))){
  echo "array must be uniq";
}

Comments

0

Just try with:

if ( count($arr) != count(array_unique($arr)) ) {
  echo 'array must be uniq';
}

Comments

0

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

Comments

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.

Comments