Current Location: Home> Latest Articles> Interview question: How to use array_flip() to determine whether the array value is unique?

Interview question: How to use array_flip() to determine whether the array value is unique?

M66 2025-06-03

In PHP, array_flip() is a very practical array function that can syndicate keys and values ​​in an array. This feature can be cleverly used to judge an array.

Function introduction

 array array_flip(array $array)

This function will return a new array, turning the key in the original array into a value , and the value into a key . But it should be noted that if there are duplicate values ​​in the original array, array_flip() will overwrite the previous key and only the last one is retained.

Therefore, we can judge whether there are duplicate values ​​by comparing the lengths of the original array and the flipped array. If the lengths of the two are inconsistent, it means that the values ​​in the original array are not unique.

Sample code

 function isArrayValuesUnique(array $arr): bool {
    $flipped = array_flip($arr);
    return count($arr) === count($flipped);
}

// Test cases
$uniqueArray = ['a' => 'apple', 'b' => 'banana', 'c' => 'cherry'];
$nonUniqueArray = ['a' => 'apple', 'b' => 'banana', 'c' => 'apple'];

echo "Unique array test results:";
echo isArrayValuesUnique($uniqueArray) ? 'It's the only one' : 'There are duplications';
echo "\n";

echo "非Unique array test results:";
echo isArrayValuesUnique($nonUniqueArray) ? 'It's the only one' : 'There are duplications';

Output:

 Unique array test results:It's the only one
非Unique array test results:There are duplications

Examples of application scenarios

Suppose you have a user registration system and need to determine whether multiple fields entered by the user (such as email, username) have duplicate values. You can use this method to quickly judge:

 $userInputs = [
    'email1' => 'user1@m66.net',
    'email2' => 'user2@m66.net',
    'email3' => 'user1@m66.net', // repeat
];

if (!isArrayValuesUnique($userInputs)) {
    echo "存在repeat的用户信息,Check, please!";
} else {
    echo "All user information is unique,Continue to process。";
}

Summarize

Using array_flip() to determine whether the array value is unique is a concise and efficient technique. Its core principle lies in the uniqueness of array keys in PHP. Once repeated values ​​occur, they will be automatically deduplicated during the flip process. We only need to compare the lengths.

This method is suitable for judging the value uniqueness of a one-dimensional array, and is a tip that is worth mastering in interviews or actual development.