I have a function that returns an array, and is passed to foreach i.e.
foreach(function() as $val)
Since the array I am returning is declared in a series of if statements, I need to return an empty array if all the if statements are evaluated to false. Is this a correct way to do it?
if (isset($arr))
return $arr;
else
return array();
I would recommend declaring
$arr = array();at the very top of the function so you don’t have to worry about it.If you are doing the check immediately before you return, I do not recommend
isset. The way you are usingforeachis depending on an array being returned. If$arris set to a number, for example, then it will still validate. You should also checkis_array(). For example:Or in one line instead:
But, like I said, I recommending declaring the array at the very top instead. It’s easier and you won’t have to worry about it.