Skip to content
Advertisement

Warning: Illegal offset type in isset or empty

I have two Doctrine entities: Page and Synonym. Each Page contains references to several Synonyms, and I want to make sure that no Synonym names are duplicated. So I create a symfony command that runs through the synonyms on a page, checking for duplicates:

protected function dedupeSynonyms(Page $page, EntityManager $em)
{
    $synonyms = $page->getSynonyms();
    $names = [];
    foreach ($synonyms as $synonym) {
        if (in_array($synonym->getName(), $names)) {
            $page->removeSynonym($synonym);
        } else {
            $names[] = $synonym->getName();
        }
        $em->persist($synonym);
    }
    $em->flush();
}

So far, so good. But when I run my command, I find that the $page->removeSynonym($synonym); line throws this ContextErrorException:

[SymfonyComponentDebugExceptionContextErrorException] Warning: Illegal offset type in isset or empty

I know that my page contains several synonyms, and I know that they contain duplicates. What am I doing wrong here?

=====

Edit: Here is my removeSynonym() function:

public function removeSynonym(Synonym $synonym)
{
        $this->synonyms->remove($synonym);

        return $this;
}

(The synonyms property is an ArrayCollection.)

Advertisement

Answer

If synonyms is an ArrayCollection you should use

$this->synonyms->removeElement($synonym);

In your way $this->synonyms->remove($synonym); it expects the key/index of the element to remove, not the element itself.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement