icecub
icecub

Reputation: 8773

PHP check if array value is unique

I was working on something earlier today and I've stumbled upon this problem. How do you check if a certain array value is unique within that array?

$array = array(1, 2, 3, 3, 4, 5);

if(unique_in_array($array, 1)) // true
if(unique_in_array($array, 3)) // false

I've been thinking about using array_search() or in_array(), but neither is very useful for finding duplicates. I'm sure I could write a function like this to do it:

function unique_in_array($arr, $search){
    $found = 0;

    foreach($arr as $val){
        if($search == $val){
            $found++;
        }
    }

    if($found > 1){
        return true;
    } else {
        return false;
    }
}

Or another solution was to use array_count_values() like this:

$array_val_count = array_count_values($array);

if($array_val_count[$search] > 1){
    return true;
} else {
    return false;
}

But it seems odd to me that PHP does not have any built-in function (or at least a better way) to do this.

Upvotes: 1

Views: 4355

Answers (3)

Khamad Ali
Khamad Ali

Reputation: 31

I have found this to check if an array has duplicate values:

$array = array(1, 2, 3, 3, 4, 5);

if(count(array_unique($array)) != count($array)){
    // Return true Array is unique
}
else{
    // Return false Array is not unique
}

Upvotes: -1

Sumon Sarker
Sumon Sarker

Reputation: 2795

You can try it like this:

$array1 = array(1, 2, 3, 3, 4, 3, 3, 5);

$func  = array_count_values($array1);
$count = $func[3];  # Pass value here

echo $count;  # This will echo 4

# If you pass an undefined value, you should use it like as below
$count = isset($func[8])? $func[8] : 0;

echo $count;  # This will echo 0, because 8 is absent in $array1

Here is the function reference of array_count_values().

Upvotes: 1

localheinz
localheinz

Reputation: 9582

Try this:

if (1 === count(array_keys($values, $value))) {
    // $value is unique in array
}

For reference, see array_keys:

Upvotes: 4

Related Questions