PHP - Optional Parameters and Default Values

Introduction

PHP can create functions with optional parameters.

You define an optional parameter as follows:


function myFunc($parameterName=defaultValue) {
         // (do stuff here)
}

Here, you insert the parameter name, followed by an equals (=) sign, followed by a default value.

This is the value that the parameter will take on if the corresponding argument is not passed when the function is called.

Demo

<?php

function helloWithStyle($font, $size=1.5) {
    echo $font . "\n";
    echo $size . "\n";
}

helloWithStyle("Helvetica", 2);
helloWithStyle("Times", 3);
helloWithStyle("Courier");

?>/*w  w w.  j a  va  2 s  . c  om*/

Result

Related Topic