w3resource

PHP Exercises: Check a flat list for duplicate values

PHP: Exercise-84 with Solution

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:

<?php
// Function definition for 'has_Duplicates' that takes an array of items as a parameter
function has_Duplicates($items)
{
    // Check if the count of items is greater than the count of unique items
    if (count($items) > count(array_unique($items)))
        // If duplicates are found, return 1 (true)
        return 1;
    else
        // If no duplicates are found, return 0 (false)
        return 0;
}

// Call 'has_Duplicates' with an array containing duplicates and display the result using 'print_r'
print_r(has_Duplicates([1, 2, 3, 4, 5, 5])); 

// Display a newline
echo "\n";

// Call 'has_Duplicates' with an array without duplicates and display the result using 'print_r'
print_r(has_Duplicates([1, 2, 3, 4, 5])); 

?>

Sample Output:

1
0

Flowchart:

Flowchart: Check a flat list for duplicate values.

PHP Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a PHP program to group the elements of an array based on the given function.
Next: Write a PHP program to get the head of a given list.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.