-1

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
1

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 !

Votes + Comments
thank rainbowMatrix
0

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 . " ";
  }
}
0

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));
}
0

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

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

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

Votes + Comments
Call them as you see them.
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.