WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

PHP 5 Functions



PHP User Defined Functions

Besides the built-in PHP functions, we can create our own functions.

A function is a block of statements that can be used repeatedly in a program.

A function will not execute immediately when a page loads.

A function will be executed by a call to the function.


Create a User Defined Function in PHP

A user defined function declaration starts with the word "function":

Syntax

function functionName() {
    code to be executed;
}

Note: A function name can start with a letter or underscore (not a number).

Tip: Give the function a name that reflects what the function does!

In the example below, we create a function named "writeMsg()". The opening curly brace ( { ) indicates the beginning of the function code and the closing curly brace ( } ) indicates the end of the function. The function outputs "Hello world!". To call the function, just write its name:

Example

<?php
function writeMsg() {
    echo "Hello world!";
}

writeMsg(); // call the function
?>
Run example »

PHP Function Arguments

Information can be passed to functions through arguments. An argument is just like a variable.

Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma.

The following example has a function with one argument ($fname). When the CustomerName() function is called, we also pass along a name (e.g. Adam L. Holden), and the name is used inside the function, which outputs several different first names, but an equal last name:

Example

<?php
function CustomerName($fname) {
    echo "$fname Refsnes.<br>";
}

CustomerName("Adam L. Holden");
CustomerName("Maria Z. Scott");
CustomerName("Betty C. Amaya");
CustomerName("Lottie P. Moore");
CustomerName("Leila J. Richert");
?>
Run example »

The following example has a function with two arguments ($fname and $year):

Example

<?php
function CustomerName($fname, $year) {
    echo "$fname Refsnes. Born in $year <br>";
}

CustomerName("Leila J. Richert", " July 23, 1987");
CustomerName("Gregory A. Ford", "January 1, 1982");
CustomerName("Robert N. Waters", "1993");
?>
Run example »

PHP Default Argument Value

The following example shows how to use a default parameter. If we call the function setHeight() without arguments it takes the default value as argument:

Example

<?php
function setHeight($minheight = 120) {
    echo "The height is : $minheight <br>";
}

setHeight(285);
setHeight(); // will use the default value of 120
setHeight(135);
setHeight(70);
?>

PHP Functions - Returning values

To let a function return a value, use the return statement: 

Example

<?php
function sum($x, $y) {
    $z = $x + $y;
    return $z;
}

echo "2 + 3 = " . sum(2, 3) . "<br>";
echo "4 + 5 = " . sum(7, 13) . "<br>";
echo "3 + 1 = " . sum(3, 1);
?>
Run example »