Php

Duplicate array values script

Posted on Updated on

Here is a way to find the duplicate values in an array.

Step 1:- Just form a simple array like this
$duplicate = array('99','98','78','99','99','78','45');
Step 2:- Now we create a function that would return the duplicate values naming against them duplicate.
function duplicate($duplicate)
{
if(!is_array($duplicate))
{
return 'Value should be in array';
}
else if(empty($duplicate))
{
return 'Empty array';
}
else
{
$result = '';
foreach($duplicate as $value)
{
if(in_array($value, $duplicate))
{
$result .= 'Duplicate - '.$value;
}
}
}
return $result;
}

In the above function first of all we check whether the input parameter is in array or not by using is_array() function, Secondly we also check whether array is empty or not by using empty() function.
After all check passed then by just using the foreach loop we iterate through all values and check each one whether it is included one time or more than one time by using a simple function in_array().

Step 3:-
echo duplicate($duplicate);
Calling the above function we get the result like this:-
Duplicate – 99
Duplicate – 98
Duplicate – 78
Duplicate – 99
Duplicate – 99
Duplicate – 78
Duplicate – 45