How to provide default values for parameters

How to assign a default value to a parameter

A function with one default parameter

function get_rand_bool_text($type = 'coin') {
  $rand = random_int(0, 1);
  switch ($type) {
    case 'coin':
        $result = ($rand == 1) ? 'heads' : 'tails';
        break;
    case 'switch':
        $result = ($rand == 1) ? 'on' : 'off';
        break;
    }
    return $result;
}
get_rand_bool_text();
echo("<p>get_rand_bool_text returns: ". get_rand_bool_text() . "</p>\n");

get_rand_bool_text returns: tails

A function with an optional parameter

function is_leap_year($date = NULL) {
  if (!isset($date)) {
    $date = new DateTime();
  }
  if ($date->format('L') == '1') {
    return true;
  } else {
    return false;
  }
}
echo("<p>Leap year = " . is_leap_year() . "</p>\n");

Leap year =

A function with one required and two default parameters

function display_error($error, $tag = 'p', $class = 'error') {
  $opentag = '<' . $tag . ' class="' . $class . '">';
  $closetag = '';
  echo $opentag . $error . $closetag;
}
display_error("This is an error message!");

This is an error message!

Calling a function with a default parameter value

Omitting optional parameters

echo get_rand_bool_text(); // Displays 'heads' or 'tails'
echo display_error('Out of range'); // 'p' tag with 'error' class
$is_leap_year = is_leap_year(); // true or false based on current date
heads

Out of range

Providing optional parameters

echo get_rand_bool_text('switch'); // Displays 'on' or 'off'
echo display_error('Out of range', 'li');

Switch is off.

  • Out of range

  • Back