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.
I want to show only common elements i.e 3,5 as output.
Answer1:
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 !
Answer 2:
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));
}
Answer 3:
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,
Answer 4:
function hasDuplicate($array) {
$defarray = array();
$filterarray = array();
foreach($array as $val){
if (isset($defarray[$val])) {
$filterarray[] = $val;
}
$defarray[$val] = $val;
}
return $filterarray;
}
Answer 5:
$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 comments:
Post a Comment