SitePoint Sponsor

User Tag List

Results 1 to 3 of 3

Hybrid View

  1. #1
    SitePoint Enthusiast
    Join Date
    Jan 2007
    Posts
    31
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Return values in a function

    Hello,

    I know this is a vauge question, but since iam new to the programming world just wanted to clarrify this silly doubts.

    Why do we need return in the function when we can use echo and get the output ?

    Can someone explain the basic of funtions ?

    Thanks in advance.

  2. #2
    SitePoint Guru Ize's Avatar
    Join Date
    Nov 2005
    Location
    The Netherlands
    Posts
    809
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Using echo inside a function is very bad practice. It almost always only works for one specific situation and can therefore never be used again in other projects.

    Furthermore, splitting up code inside functions (and better: classes) gives you more flexibility in what to do with certain data.

    For instance, let's say I've got an array, which I want to print in an HTML ordered list, but only the first 40 characters. This would work:

    PHP Code:
    function makeListFromArray ($array)
    {
      echo 
    '<ol>';
      foreach (
    $array as $a)
      {
        echo 
    '<li>' substr($a040) . '</li>';
      }
      echo 
    '</ol>';

    But that's not really flexible, is it? What if I want to print out the entire string in a different situation, should I write another function called "makeListFromArrayComplete()"? Or what if I wanted to print only 30 characters instead of 40, should I write a whole new function?
    This is where the real power of functions lies. Instead of really modifying values or printing it out directly, we can divide functionality.
    Also, we can save the return value of a function inside a variable and use it later. Remember this: separate responsibilities!

    And last but not least; in big applications a function's purpose is almost never to just output something. Most functions I write modify data and return this new data.

  3. #3
    SitePoint Member nabil_kadimi's Avatar
    Join Date
    Nov 2006
    Posts
    14
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Some times you need the value returned to give it to another function or to use it in an expression...

    PHP Code:
    function num_is_even($number){
        if( 
    $number )    return FALSE;
        else return 
    TRUE;
    }

    $test=15;
     
    if(
    num_is_even($test){
        
    //things to do if $test is even
    }

    if(!
    num_is_even($test){
        
    //things to do if $test is odd



Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •