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: heads

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

This is an 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 10 + 20 + 30 is 20

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

tails

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

Back