3

bit confused about function returns.
if i have a function with no real return needed, do i have to return 0 or return false to have a better code?

function example($time)
{
   echo $time
   //do i need to return 0 here?
};

$foodstore = array('bread','milk','meat','fruits','veges');
$buyer_list = array('bread', 'milk', 'chocolate');
function example($buyer_list , $foodstore)
{
   foeach($buyer_list as $item)
   {
       if(in_array($item, $foodstore)
        {
           return $item
        }
   }
//if i have to return only a specific $item, do i need to return 0 if no $item is specified.
}

function example($filename)
{
  $file = file_get_contents($filename);
...
  file_put_contents($filename, $file);
//do i need to return 0 here?
}
4
  • If the callers don't use the return value, you don't have to return anything. Commented Sep 8, 2017 at 23:21
  • If you don't return, it's effectively the same as return null;. Commented Sep 8, 2017 at 23:22
  • ok, i think i get it now, had to make sure. thanks. Commented Sep 8, 2017 at 23:23
  • You shouldn't print anything from a function. It should be returned, and printed when calling the function. That being said, if the function doesn't need to return something, then don't. It's not s requirement. Commented Sep 8, 2017 at 23:57

1 Answer 1

3

Just to clarify: For cleaner and more understandable code, you should always return something, if the function is not a void function. You have to ask yourself the question:

  • Why is the function not returning the desired result?
  • What should be returned in an error case?
  • Is it specified, when the function behaves different?
  • How can the caller react, if the result is unexpected.

For the last point it is necassary, that you can clearly see, what is the error value, for example by explicit add an return null; after your loop.

A good way to force you to think about your functions is to write Documentation like, PHPDoc

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

2 Comments

Your link is invalid.
Fixed, just go to the main domain TLD.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.