PHP - Returning Values from Your Functions

Introduction

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:

Demo

<?php
     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";

?>

Result

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

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

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

Related Topic