Defining a Function |PHP Tutorial For Beginners

Posted by in Articles, PHP, Programming

This is complete step by step tutorials that will help you learn basics about defining a PHP functions.

What is function?

A function is a named block of code that performs a specific task, possibly acting upon a set of values given to it, or parameters , and possibly returning a single value. Functions save on compile time no matter how many times you call them, functions are compiled only once for the page. They also improve reliability by allowing you to fix any bugs in one place, rather than everywhere you perform a task, and they improve readability by isolating code that performs specific tasks.

Function Syntax

To define a function, use the following syntax:

function [&] function_name ( [ parameter [, … ] ] )
statement list

Example – sum of two numbers

Let’s take a look at a simple function. Example 1 takes two numbers, sum them, and then returns the result

function sum($number1, $number2)
$sumNumbers=$number1 + $number2 ;
return $sumNumbers;


The function takes two arguments, $number1 and $number2. Using the + operator, the function sum the numbers in the variable $sumNumbers. Finally, we return the value $sumNumber.

How to call function sum?

echo sum(1, 2);

Output will be 3


echo sum($num1, $num2);