PHP Functions

The real power of PHP comes from its functions: it has more than 1000 built-in functions.

PHP User-Defined Functions

In addition to built-in PHP functions, we can create our own functions.

Functions are reusable blocks of statements in a program.

Functions do not execute immediately when the page is loaded.

Functions only execute when called.

Creating User-Defined Functions in PHP

User-defined function declarations start with the word "functionStarting with "

Syntax

function functionName() {
  Executed code;
}

Note:Function names can start with letters or underscores (not numbers).

Note:Function names are case-insensitive.

Tip:The function name should reflect the task performed by the function.

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

Example

<?php
function sayHi() {
  echo "Hello world!";
}
sayhi(); // Call the function
?>

Run Example

PHP Function Parameters

Information can be passed to a function through parameters. Parameters are similar to variables.

Parameters are defined after the function name, within the parentheses. You can add as many parameters as you like, just separate them with commas.

In the following example, the function has a parameter ($fname). When calling the familyName() function, we must pass a name (such as Bill) at the same time, which will output different names but the same surname:

Example

<?php
function familyName($fname) {
  echo "$fname Zhang.<br>";
}
familyName("Li");
familyName("Hong");
familyName("Tao");
familyName("Xiao Mei");
familyName("Jian");
?>

Run Example

The function in the following example has two parameters ($fname and $year):

Example

<?php
function familyName($fname,$year) {
  echo "$fname Zhang. Born in $year <br>";
}
familyName("Li","1975");
familyName("Hong","1978");
familyName("Tao","1983");
?>

Run Example

PHP Default Parameter Values

The following example shows how to use default parameters. If we call the setHeight() function without any parameters, its parameters will take the default value:

Example

<?php
function setHeight($minheight=50) {
  echo "The height is : $minheight <br>";
}
setHeight(350);
setHeight(); // It will use the default value 50
setHeight(135);
setHeight(80);
?>

Run Example

PHP Functions - Return Value

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

Example

<?php
function sum($x,$y) {
  $z=$x+$y;
  return $z;
}
echo "5 + 10 = " . sum(5,10) . "<br>";
echo "7 + 13 = " . sum(7,13) . "<br>";
echo "2 + 4 = " . sum(2,4);
?>

Run Example