PHP Exercises: Check a flat list for duplicate values
84. Duplicate Value Checker in a Flat List
Write a PHP program to check a flat list for duplicate values. Returns true if duplicate values exists and false if values are all unique.
Sample Solution:
PHP Code:
Explanation:
- Function Definition:
- The function has_Duplicates takes a single parameter, $items, which is expected to be an array.
- Count Comparison:
- The function checks if the total count of items in the array (count($items)) is greater than the count of unique items in the array (count(array_unique($items))).
- Return Value:
- If the count of items is greater than the count of unique items:
- The function returns 1 (indicating that duplicates are present).
- If the count of items is equal to the count of unique items:
- The function returns 0 (indicating that no duplicates are present).
- Example Usage with Duplicates:
- The function is called with an array containing duplicates: [1, 2, 3, 4, 5, 5].
- The result (1) is displayed using print_r, indicating that duplicates are found.
- Example Usage without Duplicates:
- The function is called with an array without duplicates: [1, 2, 3, 4, 5].
- The result (0) is displayed using print_r, indicating that no duplicates are found.
- Purpose:
- The has_Duplicates function provides a simple way to check for duplicate values in an array and returns a boolean-like result (1 for true, 0 for false) based on the presence of duplicates.
Output:
1 0
Flowchart:

For more Practice: Solve these Related Problems:
- Write a PHP script to determine if a flat array contains any duplicate values without using built-in uniqueness functions.
- Write a PHP function to scan an array and return true if duplicate elements are found.
- Write a PHP script to compare array length with the count of unique values and output a boolean for duplication.
- Write a PHP script to iterate through a list and flag if any value appears more than once.
Go to:
PREV : Group Array Elements by Callback Result.
NEXT : Retrieve the Head of a List.
PHP Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.