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.
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.
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 !
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.
3, 5,
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.
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.