13

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();

4 Answers 4

16

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 using foreach is depending on an array being returned. If $arr is set to a number, for example, then it will still validate. You should also check is_array(). For example:

if (isset($arr) && is_array($arr))
    return $arr;
else 
    return array();

Or in one line instead:

return (isset($arr) && is_array($arr)) ? $arr : array();

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I initially wanted to declare an empty array at the top, so that is how you do it.
1

To avoid complexity, Simply

return [];

Comments

0

You can simplify this code to

return (isset($arr)) ? $arr : [] ;

if it is true, return $arr else return empty array

Comments

0

Best to do it like this:

$arr = []; // declare your array upfront

// do your conditional adding and manipulating here
// if (...) $arr['abc'] = 'ABC';

return $arr; // only one return statement needed because the $arr definitely exists

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.