PHP Tutorial – Functions Parameters and Return Values

In a previous tutorial we looked at how to make your own PHP functions. In this PHP tutorial we will see how to use function parameters (for example passing a variable to a function) and function return values.

Functions Parameters

Parameters are specified after the function name, inside the parentheses.

Let’s look at a function parameter example:


<html>
<body>

<?php
    function ourFunction($x)
    {
          echo $x . ".<br />";
    }

    $y = “black”;
    echo "My car color is ";
    ourFunction("white");

    echo "My car color is ";
    ourFunction ("$y");
?>

</body>
</html>

The result of the example will be:


     My car color is white.
     My car color is black.

You can pass multiple parameters by using a comma between the parameters, for example:


function MyFunction( $X, $Y, $Z)
{
      code to be executed;
}

Function Return Values

Sometime you want to return a value if you are using functions. This is where the return statement comes in. Let’s look at an example:


<html>
<body>

<?php
     function addValues($x,$y)
     {
          $total=$x+$y;
          return $total;
     }

     echo "2 + 2 = " . addValues(2,2);
?>

</body>
</html>

You can guess the result. We pass two values to the function addValues. In the function we add the two numbers and return the total.

That’s all for this PHP tutorial.

This entry was posted in PHP Tutorials. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed. Tweet This! Tweet This! or use to share this post with others.

There are currently 3 responses to “PHP Tutorial – Functions Parameters and Return Values”

Why not let us know what you think by adding your own comment!

  1. Vikas Kumar on February 9th, 2013:

    Thanks ..
    its very to learn here…..

  2. puran singh on July 1st, 2013:

    thanks for this tutorial. it help’s me to learn php.

  3. achyut on December 30th, 2013:

    thanks…
    its very clear explanation…