Search code examples
phparraysunique

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.


Solution

  • Try this:

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

    For reference, see array_keys: