0

I am new to PHP and am trying to remove duplicate entries in an array. I end up with my desired output, but I am also getting two "Undefined offset" errors along the way. This is the code I have: $this->master refers to an array declared in the beginning of the class.

    public function removeDuplicates(){
        $var = count($this->master);
            for($i = 0; $i < $var; $i++){
                    for($j = 0; $j <$var; $j++){
                        if(($this->master[$i] == $this->master[$j]) && $i != $j){                           
                            $this->shiftLeft($j, $var);
                            $var --;
                        }
                    }
            }
    }

    public function shiftLeft($t, $s){
        while($t < $s){
            echo "$t ";
            $this->master[$t] = $this->master[$t+1];
            $t++;
        }
        unset($this->master[$t-1]);
    }

It is probably a really simple logical error but I cannot seem to find where. Any help is greatly appreciated.

2

1 Answer 1

2

See if it works

 $unique = array_unique($this->master);
Sign up to request clarification or add additional context in comments.

2 Comments

That gives me an array of the duplicate entries, without any of the non-duplicates. How can I have if give me an array of only one instance of the duplicates? So if the array was (a,b,a,c) the new array would be (a,b,c)? @andreas
Are you sure that is what it's doing? It's supposed to give you the array without dupes, not the dupes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.