PHP Built-in Functions
PHP comes with more than 1000 built-in functions, each doing a specific job, and you can call any of them directly from your script. For the full list, see our PHP reference.
PHP User Defined Functions
You aren't limited to what PHP provides, because you can also write functions of your own.
- Think of a function as a group of statements you can reuse throughout a program.
- Loading a page doesn't run it on its own.
- Its code runs only when you call it.
Create a Function
To declare your own function, write the keyword function and then the name you want to give it.
The function's code goes between a pair of curly braces: { marks where it begins and } marks where it ends.
Note: Function names must begin with a letter or an underscore, and PHP ignores their letter case.
Tip: Choose a name that says what the function does, so your code is easier to read.
Function Syntax
The general shape of a function you define yourself:
function functionName($parameter1, $parameter2) {
// code to be executed
return $value; // optional
}
Create a Function Example
Here is a real one, called myMessage(), that prints a greeting:
function myMessage() {
echo "Hello world!";
}
Call a Function
Calling a function takes nothing more than its name and a pair of parentheses ().
When called, this one prints "Hello world!":
Call a Function
First define myMessage(), then run it by calling it:
Output: PHP script
<?php
function myMessage() {
echo "Hello world!";
}
myMessage();
?>
PHP Function Parameters
Parameters are how you hand information to a function. Inside the function, a parameter behaves just like a variable.
List them inside the parentheses after the function's name, with a comma between each one. There is no limit on how many you can add.
Function With One Parameter
familyName() takes a single parameter, $fname. Each call passes in a different first name, which the function combines with the same last name, so every line of output shows a new first name with "Refsnes" after it:
Output: PHP script
<?php
function familyName($fname) {
echo "$fname Refsnes.<br>";
}
familyName("Jani");
familyName("Hege");
familyName("Stale");
familyName("Kai Jim");
familyName("Borge");
?>
Function With Two Parameters
This version takes two parameters, $fname and $year, and prints both:
Output: PHP script
<?php
function familyName($fname, $year) {
echo "$fname Refsnes. Born in $year.<br>";
}
familyName("Hege", "1975");
familyName("Stale", "1978");
familyName("Kai Jim", "1983");
?>
PHP Default Parameter Value
A parameter can have a fallback value. Here, calling setHeight() with no argument means it uses its default instead:
Default Parameter Value
The first call passes 350; the second passes nothing, so $height falls back to 50:
Output: PHP script
<?php
function setHeight($height = 50) {
echo "The height is : $height <br>";
}
setHeight(350);
setHeight(); // will take the default value of 50
?>
PHP Functions - Returning values
When a function reaches return, it stops right there and sends a value back to the line of code that called it:
Returning Values
sum() adds its two arguments and gives the total back to the caller:
Output: PHP script
<?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);
?>
Passing Arguments by Reference
By default, arguments are passed by value: the function works on a copy, so the original variable you passed in stays unchanged.
Passing by reference removes that copy, which means anything the function does to the argument also happens to the original variable. To set this up, put the & operator in front of the parameter:
Pass by Reference
Because $value is a reference, add_five() changes $num itself, from 2 to 7:
Output: PHP script
<?php
function add_five(&$value) {
$value += 5;
}
$num = 2;
add_five($num);
echo $num;
?>
Variable Number of Parameters
Sometimes you can't know in advance how many values a function will receive. Put the ... operator in front of a parameter and it will accept any number of them. A function like this is called a variadic function.
All the values collected by that parameter arrive as an array.
There are two rules: a function can have only one variable-length parameter, and it must come last. Put it anywhere else and PHP reports an error.
Variadic Function
sumMyNumbers() adds up however many numbers it is given, in this case six:
Output: PHP script
<?php
function sumMyNumbers(...$x) {
$n = 0;
$len = count($x);
for($i = 0; $i < $len; $i++) {
$n += $x[$i];
}
return $n;
}
$a = sumMyNumbers(5, 2, 6, 2, 7, 7);
echo $a;
?>
Variadic as Last Argument
A normal parameter can come first, as long as the variadic one is in the last position:
Output: PHP script
<?php
function myFamily($lastname, ...$firstname) {
$txt = "";
$len = count($firstname);
for($i = 0; $i < $len; $i++) {
$txt = $txt."Hi, $firstname[$i] $lastname.<br>";
}
return $txt;
}
$a = myFamily("Doe", "Jane", "John", "Joey");
echo $a;
?>
Variadic Not Last Argument Error
Here ... is on the first of two parameters, so the code fails with an error:
Output: PHP script
<?php
function myFamily(...$firstname, $lastname) {
$txt = "";
$len = count($firstname);
for($i = 0; $i < $len; $i++) {
$txt = $txt."Hi, $firstname[$i] $lastname.<br>";
}
return $txt;
}
$a = myFamily("Doe", "Jane", "John", "Joey");
echo $a;
?>
PHP is a Loosely Typed Language
You may have noticed that none of the examples so far told PHP what data type a variable holds.
That's because PHP works out the type for itself from the variable's value. With no types enforced, you can do things like add a numeric string such as "5" to an integer, and no error occurs.
Type declarations arrived in PHP 7. They let you state which data type you expect when you declare a function. Turn on the strict declaration as well, and a mismatched type stops the script with a "Fatal Error".
You enable strict mode with declare(strict_types=1);, which has to be the very first statement in the PHP file.
Strict Mode
The strict declaration is on here, and the function receives a number and a string. Because "5 days" isn't an integer, the script ends with an error:
Output: PHP script
<?php declare(strict_types=1); // strict requirement
function addNumbers(int $a, int $b) {
return $a + $b;
}
echo addNumbers(5, "5 days");
// since "5 days" is not an integer, an error will be thrown
?>
PHP Return Type Declarations
Type declarations work for the return statement too.
To set the type a function gives back, write a colon : and the type just before the opening curly { bracket in the declaration.
Return Type Declaration
This function declares float as its return type:
Output: PHP script
<?php declare(strict_types=1); // strict requirement
function addNumbers(float $a, float $b) : float {
return $a + $b;
}
echo addNumbers(1.2, 5.2);
?>
Different Return Type
The return type doesn't have to match the argument types, as long as the value you return really is of the declared type. Here, the float result is cast to an int:
Output: PHP script
<?php declare(strict_types=1); // strict requirement
function addNumbers(float $a, float $b) : int {
return (int)($a + $b);
}
echo addNumbers(1.2, 5.2);
?>