How to Create and call a Function
Function syntax
function function_name([$param_1, $param_2, ... , $param_n]) {
// Code for function
[return [value];] // optional
}
How to define a function
A function with no parameters that returns a value
function coin_toss() {
$coin = (random_int(0, 1) == 0) ? 'heads' : 'tails'; // ternary conditional
return $coin;
}
Coin is: $coin");
?>
A function with one parameter
$error = "This is an error!";
function display_error($error) {
echo("<p class='error'>$error</p>\n");
}
Calling a Function
display_error($error);
Output
$error\n");
}
display_error($error);
?>
A function with three parameters that returns a value
$x = 10;
$y = 20;
$z = 30;
function avg_of_3($x, $y, $z) {
$avg = ($x + $y + $z) / 3;
return $avg;
}
avg_of_3($x, $y, $z);
echo("<p>Average of $x + $y + $z is " . avg_of_3($x, $y, $z) . "</p>\n");
Average of $x + $y + $z is " . avg_of_3($x, $y, $z) . "\n");
?>
How to call a function
Functions that return values
$average = avg_of_3(5, 2, 8); // average is 5
echo coin_toss(); // display heads or tails
Output
A function that doesn’t return a value
display_error('Value out of range.');
Discarding the return value
$list = array('Apples', 'Oranges', 'Grapes');
$last = array_pop($list); // Removes Grapes – stores return value
array_pop($list); // Removes Oranges – discards return value
- A function is a reusable block of code. To code a function, code the function keyword followed by the name of the function, followed by a set of parentheses.
- Within the parentheses of a function, you can code an optional parameter list that contains one or more parameters.
- To code a function that returns data, code a return statement in the body of the function. The return statement ends the execution of the function and returns the specified value. If you don’t specify a value in the return statement, it returns NULL.
- To code a function that doesn’t return data, don’t include a return statement.
- When you call a function, the arguments in the argument list must be in the same order as the parameters in the parameter list defined by the function, and they must have compatible data types.
Back