PHP - Returning Values from Your Functions


To get your function to return a value, you use - you guessed it - PHP's return statement:

function myFunc() {
          // (do stuff here)
          return value;

value can be any expression.

You can use a literal value (such as 1 or false), a variable name (such as $result), or a more complex expression (for example, $x * 3 / 7).

When PHP encounters the return statement, it exits the function and returns value back to the code that called the function.

The following example script shows how to define and use a function that returns a value:


     function makeBold($text) {
      return "$text is bold";
     }/*from   w w w  . ja  v  a2  s .c  o  m*/

     $normalText ="This is normal text.";
     $boldText = makeBold("This is bold text.");
     echo "$normalText\n";
     echo "$boldText\n";



You can use the return statement without including a value to return:

function myFunc() {
         // (do stuff here)

This simply exits the function at that point, and returns control to the calling code.

Related Topic