Make a function in PHP to find duplicates

duplicated element

As common as posible, if you are looking for a job, hopefully you will be challenged to an online code review. You should select the language, of course.

Some cases you might prepare your environment before interview, but if you don’t have enough time, I should recommend some of this amazing online tools:

  • https://codesandbox.io/
  • https://codepen.io/

A complete environment to test your first coding.

To the point, in the following lines you should see my version about How to find a duplicate over an array structure

  • TempArray is needed to store each repeated value, it will be useful to ask in next iteration

This is one of it.

<?php
function findDuplicates($integerArray){
  $tempArray=$integerArray;

  // Verify each element
  $repetead=[];
  foreach ($integerArray as $index=>$item){
    if (in_array($item,$repetead) ){
      continue;
    }
    unset($tempArray[$index]);
    if(	in_array($item,$tempArray) ){
      array_push($repetead, $item);
    }
    
  }
  return $repetead;
}
$array=[3, 3, 2, 1, 1, 3,4,4,8];
var_dump (findDuplicates($array));

 

Deja una respuesta