Returning Values from User-Defined Functions

In the previous example, we output an amended string to the browser within the printBR() function. Sometimes, however, you will want a function to provide you with a value that you can work with yourself. If your function has transformed a string that you have provided, you may wish to get the amended string back so that you can pass it to other functions. A function can return a value using the return statement in conjunction with a value. The return statement stops the execution of the function and sends the value back to the calling code.

Listing 6.4 creates a function that returns the sum of two numbers.

Listing 6.4 A Function That Returns a Value
  1: <html>
  2: <head>
  3: <title>Listing 6.4</title>
  4: </head>
  5: <body>
  6: <?php
  7: function addNums( $firstnum, $secondnum ) {
  8:     $result = $firstnum + $secondnum;
  9:     return $result;
 10: }
 11: print addNums(3,5);
 12: // will print "8"
 13: ?>
 14: </body>
 15: </html>

Put these lines into a text file called addnums.php, and place this file in your Web server document root. When you access this script through your Web browser, it produces the following:


Notice in line 7 that addNums() should be called with two numeric arguments (line 11 shows those to be 3 and 5 in this case). These are stored in the variables $firstnum and $secondnum. Predictably, addNums() adds the numbers contained in these variables together and stores the result in a variable called $result.

The return statement can return a value or nothing at all. How we arrive at a value passed by return can vary. The value can be hard-coded:

return 4;

It can be the result of an expression:

return ( $a/$b );

It can be the value returned by yet another function call:

return ( another_function( $an_argument ) );

    Part III: Getting Involved with the Code