Learning Resources
 

Parameter and return values


Functions are used extensively in computer languages and spreadsheets. A function takes an input , does some calculations on the input, and then gives back a result. In computer programming they are a very similar idea, with a few changes to naming and properties.

A function in a PHP is a program fragment that 'knows' how to perform a defined task. For example a function may be written that finds the average of three supplied numbers. Once written, this function may be used many times without having to rewrite it over and over.
Example - the function avg

function avg(a,b,c)
{ var result = (a+b+c)/3;
  return result;
}

The above, written in Javascript, performs the average function. On the first line, the name of the function is 'avg', It expects three inputs called a,b and c. In computer programming these are called parameters; they stand for the three values sent when the function is used. The function has it's own private variable called result which is calculated from the parameters and then the function 'returns' the result;
Using the function

In PHP the act of using the function is "calling the function". In the program below there are two "calls" to the function. In each case, three particular values are sent as parameters and the result will be the average of the three.

/* main program*/
..
var averageHt = avg(6, 4, 7);
..
..
var averageAge = avg(30, 45, 21);
..

Functions are very similar to those in math, and serve to 'package' some calculations so it can be separated and used over and over.

A function has a name to call it by, and a list of zero or more arguments or parameters that is handed to it for it to act on or to direct its work; it has a body containing the actual instructions (statements) for carrying out the task the function is supposed to perform; and it may give back a return value, of a particular type.

Here is a very simple function, which accepts one argument, multiplies it by 2, and hands that value back:

	int multbytwo(int x)
	{
		int retval;
		retval = x * 2;
		return retval;
	}

On the first line we see the return type of the function (int), the name of the function (multbytwo), and a list of the function's arguments, enclosed in parentheses. Each argument has both a name and a type; multbytwo accepts one argument, of type int, named x. The name x is arbitrary, and is used only within the definition of multbytwo. The caller of this function only needs to know that a single argument of type int is expected; the caller does not need to know what name the function will use internally to refer to that argument. (In particular, the caller does not have to pass the value of a variable named x.)