PHP - Functions with Parameters

You can specify parameters when you define your function to accept input values at run time. The parameters work like placeholder variables within a function; they're replaced at run time by the values (known as argument) provided to the function at the time of invocation.

function myFunc($oneParameter, $anotherParameter){

    // Code to be executed

}

You can define as many parameters as you like. However for each parameter you specify, a corresponding argument needs to be passed to the function when it is called.

The getSum() function in following example takes two integer values as arguments, simply add them together and then display the result in the browser.

<?php

// Defining function

function getSum($num1, $num2){

  $sum = $num1 + $num2;

  echo "Sum of the two numbers $num1 and $num2 is : $sum";

}

// Calling function

getSum(10, 20);

?>

The output of the above code will be:

Sum of the two numbers 10 and 20 is : 30

 

Functions with Optional Parameters and Default Values

You can also create functions with optional parameters — just insert the parameter name, followed by an equals (=) sign, followed by a default value, like this.

<?php

// Defining function

function customFont($font, $size=1.5){

    echo "<p style=\"font-family: $font; font-size: {$size}em;\">Hello, world!</p>";

}

// Calling function

customFont("Arial", 2);

customFont("Times", 3);

customFont("Courier");

?>

 

Returning Values from a Function

A function can return a value back to the script that called the function using the return statement. The value may be of any type, including arrays and objects.

<?php

// Defining function

function getSum($num1, $num2){

    $total = $num1 + $num2;

    return $total;

}

// Printing returned value

echo getSum(5, 10); // Outputs: 15

?>

A function can not return multiple values. However, you can obtain similar results by returning an array.

 

Passing Arguments to a Function by Reference

In PHP there are two ways you can pass arguments to a function: by value and by reference. By default, function arguments are passed by value so that if the value of the argument within the function is changed, it does not get affected outside of the function. However, to allow a function to modify its arguments, they must be passed by reference.

Passing an argument by reference is done by prepending an ampersand (&) to the argument name in the function definition, as shown in the example below:

<?php

/* Defining a function that multiply a number

by itself and return the new value */

function selfMultiply(&$number){

    $number *= $number;

    return $number;

}

$mynum = 5;

echo $mynum; // Outputs: 5

 

selfMultiply($mynum);

echo $mynum; // Outputs: 25

?>