Reputation: 8346
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
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,
Upvotes: 1
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