Lukas Lukac
Lukas Lukac

Reputation: 8346

symfony undefined variable after empty query passing to twig

I have function in my repository... everything works greate when they are some data... but when not:

error: undefined variable $followees_ids appear...

public function foreachFolloweesToFolloweesIds($followees)
{
    foreach ($followees as $followee) {
        $followees_ids[]=$followee['id'];
    } 

    if (empty($followees_ids)) {
        return NULL;
    } else {
        return $followees_ids;
    }
}

It could be done as i wrote if (empty ... bla bla but it seems to be not written very well... and i will use it a lot so some best practise would be greate. How can i write it better to defend the variable from being undefined?

Upvotes: 1

Views: 432

Answers (2)

Ahmed Siouani
Ahmed Siouani

Reputation: 13891

So basically, your method returns an array of (what you called) followees_ids,

Even if I don't understand what this method is used for, I would suggest using Early return to check if $followees contains elements.

So, you've to add on the top of your method,

if (empty($followees)) {
    return array(); // or null
}

Also,

  • You've to first initialize the array your method returns.
  • You don't really need an else statement when you return early.

Upvotes: 1

hacfi
hacfi

Reputation: 766

Just put a

$followees_ids = array();

before the foreach so $followees_ids isn't undefined even if you don't have any results.

Upvotes: 1

Related Questions