Home > Blockchain >  PHP function to remove duplicate strings in an array
PHP function to remove duplicate strings in an array

Time:11-13

function removeDuplicates($arr)
      {
        $newArr = [];
        for ($i=0; $i<count($arr); $i  ){
            if (array_search($arr[$i], $newArr) == false) {
               array_push($newArr, $arr[$i]); 
            }
        }
        foreach ($newArr as $element){
         print "$element <br>";
        }
         
      }

 

$dup = removeDuplicates(["cat", "box", "dog", "cat", "box", "dog", "tree", "dog", "tree"]);
print $dup;

results of the function is:

cat
box
dog
cat
tree

I am trying to make this function named removeDuplicates take an array of strings as parameter and return a duplicate free array. The calling/parameter array does not change. The unique strings of the calling array are placed in a newly created array and it is returned. would appreciate it if someone pointed out where the issue is in my code or why it looks like some duplicates are removed but not all.

CodePudding user response:

I recommend you using a Set data structure, please take a look. https://www.php.net/manual/en/class.ds-set.php

CodePudding user response:

Your solution is too large. Use array_unique() function. It will remove duplicated cases from array.

print_r(array_unique([‘dog’,’dog’,’cat’]);
  • Related