Monday, 27 August 2018

PHP - show only duplicate values from array without builtin function

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.

Answer1:
The logic here is simple:
I am not a php developer so i am using c++ to explain this method !
  1. int Array[6]= {3,5,2,5,3,9};
  2. //create a for-loop for ArrayA
  3. for(int i=0; i<6; i++)
  4. {
  5. //create a for-loop for checking element from ArrayA is equal to any other element
  6. for(int s=0; s<6; s++)
  7. {
  8. // to check if terms are equal (note i!=s)
  9. if(Array[i]==Array[s] && i!=s)
  10. {
  11. //Print Array elements or store it in another array and the use any unique array function to see unique elements !
  12. }
  13. }
  14. }
Try to make the code for php yourself !
Answer 2:
How about something outside of the box:
  1. $array = array(3, 5, 2, 5, 3, 9);
  2. $duplicates = array_duplicates($array);
  3. function array_duplicates(array $array)
  4. {
  5. return array_diff_assoc($array, array_unique($array));
  6. }
Answer 3:
Finally got there:
  1. <?php
  2. $arr = array(3,5,2,5,3,9);
  3. $temp_array = array();
  4. foreach($arr as $val)
  5. {
  6. if(isset($temp_array[$val]))
  7. {
  8. $temp_array[$val] = $val;
  9. }else{
  10. $temp_array[$val] = 0;
  11. }
  12. }
  13. foreach($temp_array as $val2)
  14. {
  15. if($val2 > 0)
  16. {
  17. echo $val2 . ', ';
  18. }
  19. }
  20. ?>
I doubt it will work for words, or characters, for this you will have to manipulate the array_keys.

Output:

3, 5,
Answer 4:
  1. function hasDuplicate($array) {
  2. $defarray = array();
  3. $filterarray = array();
  4. foreach($array as $val){
  5. if (isset($defarray[$val])) {
  6. $filterarray[] = $val;
  7. }
  8. $defarray[$val] = $val;
  9. }
  10. return $filterarray;
  11. }



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


0 comments:

Post a Comment