How to create functions in PHP

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

Syntax

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;
}

Code

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 ();.

<?php
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.

<?php
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).

<?php
function addValues($value1, $value2){
$total = $value1 + $value2;
return $total;
}
echo addValues(8, 20); // Outputs: 28
?>
Copyright ©2024 Educative, Inc. All rights reserved