Show only duplicate values from array without built in function

\$arr = array(3,5,2,5,3,9);
I want to show only common elements i.e 3,5 as output.

Edited by rajendra87

6
Contributors
7
Replies
16
Views
5 Years
Discussion Span
Last Post by diafol

The logic here is simple:

I am not a php developer so i am using c++ to explain this method !

``````int Array[6]= {3,5,2,5,3,9};

//create a for-loop for ArrayA

for(int i=0; i<6; i++)
{

//create a for-loop for checking element from ArrayA is equal to any other element

for(int s=0; s<6; s++)
{

// to check if terms are equal (note i!=s)

if(Array[i]==Array[s] && i!=s)
{

//Print Array elements or store it in another array and the use any unique array function to see unique elements !
}
}
}
``````

Try to make the code for php yourself !

thank rainbowMatrix

I saw this same question here ! if you did not post it then here is the code:

``````\$arr = array(3,5,2,5,3,9);
foreach(\$arr as \$key => \$val){
//remove the item from the array in order
//to prevent printing duplicates twice
unset(\$arr[\$key]);
//now if another copy of this key still exists in the array
//print it since it's a dup
if (in_array(\$val,\$arr)){
echo \$val . " ";
}
}
``````

that question was posted by me @rainbowMatrix

How about something outside of the box:

``````\$array = array(3, 5, 2, 5, 3, 9);
\$duplicates = array_duplicates(\$array);

function array_duplicates(array \$array)
{
return array_diff_assoc(\$array, array_unique(\$array));
}
``````

Finally got there:

``````<?php

\$arr = array(3,5,2,5,3,9);
\$temp_array = array();

foreach(\$arr as \$val)
{
if(isset(\$temp_array[\$val]))
{
\$temp_array[\$val] = \$val;
}else{
\$temp_array[\$val] = 0;
}
}

foreach(\$temp_array as \$val2)
{
if(\$val2 > 0)
{
echo \$val2 . ', ';
}
}

?>
``````

I doubt it will work for words, or characters, for this you will have to manipulate the array_keys.

## Output:

3, 5,

Edited by phorce

``````function hasDuplicate(\$array) {
\$defarray = array();
\$filterarray = array();
foreach(\$array as \$val){
if (isset(\$defarray[\$val])) {
\$filterarray[] = \$val;
}
\$defarray[\$val] = \$val;
}
return \$filterarray;
}
``````

Thanks for necroposting this dead thread back to the current list - not.