Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags


How to create functions in PHP

Educative Answers Team

A function is a block of statements that can be used repeatedly in a program. Functions are only executed in a program when called.


PHP allows users to define their own functions. A user-defined function declaration starts with the keyword function and contains all the code inside the {} braces.

function functionName() {
    code to be executed;


In the example below, we create a function named hello(). ​The function outputs “Hello world!”. To call this function, write its name followed by brackets ();.

function hello() {   // defining the function
    echo "Hello world!";

hello();   // calling the function

Functions with arguments

PHP functions can also have parameters passed to them. A function can have as many parameters as it wants. These parameters work like variables inside of our function.

function bornIn($name, $year) {
    echo "$name was born in $year \n";

bornIn("Kim", "1960");
bornIn("Jon", "1998");
bornIn("Tim", "1990");

Functions with return values

A function can return a value to the script that called the function using the return statement. The return value may be of any type (including arrays and objects).

function addValues($value1, $value2){
    $total = $value1 + $value2;
    return $total;
echo addValues(8, 20); // Outputs: 28


Copyright ©2022 Educative, Inc. All rights reserved

View all Courses

Keep Exploring