In PHP, a function is a piece of code which takes one or more inputs in the form of parameters and does some processing then returns a value. You already have seen many functions like echo(), print_r(), var_dump(), etc. These are built-in functions, but PHP also allows you to create your own functions.

Defining a Function

A function is defined using the function keyword, followed by a name and parentheses ():

function writeMsg() {
    echo "Hello world!";

writeMsg(); // call the function

Function Parameters

Information can be passed to functions through parameters:

phpCopy code<?php
function familyName($fname) {
    echo "$fname Smith.<br>";

familyName("Kai Jim");

Function Return Value

A function can return a value using the return statement:

phpCopy code<?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);

Functions are a way of encapsulating functionality that you wish to reuse. It makes your code more modular and easier to understand.

Last updated