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 has_Duplicates($items)
{
    if (count($items) > count(array_unique($items)))
      return 1;
    else
      return 0;
}
print_r(has_Duplicates([1, 2, 3, 4, 5, 5])); 
echo "\n";
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.

PHP: Tips of the Day

Mutates the original array to filter out the values specified

Example:

<?php
function tips_pull(&$items, ...$params)
{
  $items = array_values(array_diff($items, $params));
  return $items;
}

$items = ['x', 'y', 'z', 'x', 'y', 'z'];
print_r(tips_pull($items, 'y', 'z'));
?>

Output:

Array
(
    [0] => x
    [1] => x
)