3

I am trying to remove an Article object from an array inside a foreach loop but I am getting the error Fatal error: Cannot use object of type Article as array

foreach ($articles as $i => $article) {
    foreach ($categorys as $category) {

        if (checkCategory($category,$article)) {
            unset($article[$i]);
        }
    }
    if ($userName != Null) {
        if ($article->getUserName() != $userName) {
            unset($article[$i]);
        }
    }
    if ($keyWords != Null) {
        if (!containsKeyWords($keyWords, $article)) {
            unset($article[$i]);
        }
    }
}
3
  • can you show ho's your object look like. some values? Commented May 1, 2017 at 4:37
  • 5
    You have a simple typo... use unset($articles[$i]). Commented May 1, 2017 at 4:37
  • Where does the categorys array come from? Commented May 1, 2017 at 4:37

3 Answers 3

2

You have to unset from $articles array(main or parent array).so do like below:-

unset($articles[$i])
Sign up to request clarification or add additional context in comments.

Comments

0

The error gives me some clue that your $article may not be an array but an stdClass Object, you can usevar_dump to check its type.

you can unset an object using unset($article->{$i}) or unset($article->somekey).

Hope it helps.

Comments

0

$article is of an Object type and you're trying to access it via array type.

Try var_dump() to check it's type & then accordingly use unset.

For array type : unset($article[$i])
For object type : unset($article->{$i}) where $i is key

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.