- PHP Functions
- What is a function
- Why do you need functions in the first place?
- Define a function
- Call a function
- Parameters vs. arguments
- Return a value
- HTML code inside the function
- Summary
- PHP Functions
- PHP Built-in Functions
- PHP User Defined Functions
- Create a User Defined Function in PHP
- Syntax
- Example
- PHP Function Arguments
- Example
- Example
- PHP is a Loosely Typed Language
- Example
- Example
- PHP Default Argument Value
- Example
- PHP Functions — Returning values
- Example
- PHP Return Type Declarations
- Example
- Example
- Passing Arguments by Reference
- Example
PHP Functions
Summary: in this tutorial, you will learn about PHP functions and how to define user-defined functions.
What is a function
A function is a named block of code that performs a specific task.
So far, you have learned how to use built-in functions in PHP, such as var_dump() that dumps information about a variable.
In this tutorial, you’ll learn how to define your functions. These functions are called user-defined functions.
Why do you need functions in the first place?
Sometimes, you need to perform the same task multiple times in a script. For example, suppose that you want to show a message that welcomes a user like this:
echo 'Welcome!';
Code language: HTML, XML (xml)
If you want to show the same message in other places, you must copy the above statement and paste it in many places.
But when you want to change the message from Welcome! to Welcome Back ! you need to change it in various places. It’ll make the code very difficult to maintain.
This is where functions come into play. A function allows you to assign a name to a code block and reuse that code block in multiple places without duplicating the code.
To define and call a user-defined function, you use the following steps:
First, define a function called welcome() like this:
function welcome() < echo 'Welcome!'; >
Code language: HTML, XML (xml)
Then, call the welcome() function in any place where you want to show the welcome message:
welcome();
Code language: HTML, XML (xml)
Later, if you want to have a different message, you can change it centrally in the welcome() function instead of in multiple places.
By using a function, you can reuse a code block and make your script easier to maintain.
Define a function
To define a function, you use the following syntax:
function function_name()
Code language: HTML, XML (xml)
- First, specify the function name followed by the function keyword. The name of the function needs to start with a letter or underscore followed by zero or more letters, underscores, and digits.
- Second, define one or more statements inside the function body. The function body starts with the < and ends with >.
Like the above example, you can define a function called welcome() as follows:
function welcome() < echo 'Welcome'; >
Code language: HTML, XML (xml)
In this example, the function name is welcome . The welcome() function displays the welcome message.
The welcome() function doesn’t have input. It shows the welcome message.
In practice, functions often accept inputs. The inputs make functions reusable and more useful. And the inputs of a function are called parameters.
A function may have zero or more parameters. To add one or more parameters to a function, you can use the following syntax:
function function_name(parameter1, parameter2, . )
Code language: HTML, XML (xml)
Inside the function body, you can use the parameters like variables. In fact, parameters are the local variables.
For example, if you want to welcome users by their usernames, you can add a $username parameter to the welcome function as follows:
function welcome_user($username) < echo 'Welcome ' . $username; >
Code language: HTML, XML (xml)
The welcome_user() function has a parameter $username . It displays a welcome message to the user by concatenating the Welcome message with $username .
Call a function
When a function doesn’t have any parameter, you can call the function by using its name followed by parentheses like this:
function_name();
Code language: HTML, XML (xml)
function welcome() < echo 'Welcome!'; > welcome();
Code language: HTML, XML (xml)
The welcome() function shows the following message:
And when you call the function with parameters, you need to pass arguments into it:
The following example calls the welcome_user() function:
function welcome_user($username) < echo 'Welcome ' . $username; > welcome_user('Admin');
Code language: HTML, XML (xml)
In this example, we passed the ‘Admin’ argument to the welcome_user() function. The function displays the following message:
Inside the welcome_user() function, the value of the $username is ‘Admin ‘.
If you pass another argument into the function, the message will change. For example:
welcome_user('Guest');
Code language: HTML, XML (xml)
Parameters vs. arguments
The terms parameters and arguments are often used interchangeably. However, they’re slightly different.
When you define a function that accepts inputs, you specify the parameters. In this example, $username is a function parameter:
function welcome_user($username) < echo 'Welcome ' . $username . '!'; >
Code language: HTML, XML (xml)
An argument is a piece of data that you pass into the function when you call it. In the following function call, the literal string ‘Admin’ is an argument:
welcome_user('Admin');
Code language: HTML, XML (xml)
Return a value
A function can return a value. To return a value from a function, you use the return statement:
return value;
Code language: JavaScript (javascript)
The return statement immediately ends the execution of the current function and returns the value.
The value can be a literal value like a number and a string. Also, it can be a variable or an expression.
The following function returns a welcome message instead of displaying it:
function welcome_user($username) < return 'Welcome '. $username . '!'; >
Code language: HTML, XML (xml)
Since the welcome_user() function returns a string, you can assign its return value to a variable like this:
$welcome_message = welcome_user('Admin');
Code language: PHP (php)
echo welcome_user(); ?>
Code language: HTML, XML (xml)
HTML code inside the function
Typically, a function contains only PHP code. However, it’s possible to define a function that contains HTML code. The following welcome() function displays the welcome message wrapped in a span tag:
function welcome_user($username) < ?> span>Welcome = $username ?> span>
> ?> Code language: HTML, XML (xml)
Summary
- A function is a named block of code that performs a specific task.
- Do use functions to create reusable code.
- Use the return statement to return a value from a function.
PHP Functions
PHP has more than 1000 built-in functions, and in addition you can create your own custom functions.
PHP Built-in Functions
PHP has over 1000 built-in functions that can be called directly, from within a script, to perform a specific task.
Please check out our PHP reference for a complete overview of the PHP built-in functions.
PHP User Defined Functions
Besides the built-in PHP functions, it is possible to create your own functions.
- A function is a block of statements that can be used repeatedly in a program.
- A function will not execute automatically when a page loads.
- A function will be executed by a call to the function.
Create a User Defined Function in PHP
A user-defined function declaration starts with the word function :
Syntax
Note: A function name must start with a letter or an underscore. Function names are NOT case-sensitive.
Tip: Give the function a name that reflects what the function does!
In the example below, we create a function named «writeMsg()». The opening curly brace ( < ) indicates the beginning of the function code, and the closing curly brace ( >) indicates the end of the function. The function outputs «Hello world!». To call the function, just write its name followed by brackets ():
Example
writeMsg(); // call the function
?>
PHP Function Arguments
Information can be passed to functions through arguments. An argument is just like a variable.
Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma.
The following example has a function with one argument ($fname). When the familyName() function is called, we also pass along a name (e.g. Jani), and the name is used inside the function, which outputs several different first names, but an equal last name:
Example
familyName(«Jani»);
familyName(«Hege»);
familyName(«Stale»);
familyName(«Kai Jim»);
familyName(«Borge»);
?>
The following example has a function with two arguments ($fname and $year):
Example
function familyName($fname, $year) echo «$fname Refsnes. Born in $year
«;
>
?php
familyName(«Hege», «1975»);
familyName(«Stale», «1978»);
familyName(«Kai Jim», «1983»);
?>
PHP is a Loosely Typed Language
In the example above, notice that we did not have to tell PHP which data type the variable is.
PHP automatically associates a data type to the variable, depending on its value. Since the data types are not set in a strict sense, you can do things like adding a string to an integer without causing an error.
In PHP 7, type declarations were added. This gives us an option to specify the expected data type when declaring a function, and by adding the strict declaration, it will throw a «Fatal Error» if the data type mismatches.
In the following example we try to send both a number and a string to the function without using strict :
Example
function addNumbers(int $a, int $b) return $a + $b;
>
echo addNumbers(5, «5 days»);
// since strict is NOT enabled «5 days» is changed to int(5), and it will return 10
?>?php
To specify strict we need to set declare(strict_types=1); . This must be on the very first line of the PHP file.
In the following example we try to send both a number and a string to the function, but here we have added the strict declaration:
Example
function addNumbers(int $a, int $b) return $a + $b;
>
echo addNumbers(5, «5 days»);
// since strict is enabled and «5 days» is not an integer, an error will be thrown
?>
The strict declaration forces things to be used in the intended way.
PHP Default Argument Value
The following example shows how to use a default parameter. If we call the function setHeight() without arguments it takes the default value as argument:
Example
setHeight(350);
setHeight(); // will use the default value of 50
setHeight(135);
setHeight(80);
?>
PHP Functions — Returning values
To let a function return a value, use the return statement:
Example
PHP Return Type Declarations
PHP 7 also supports Type Declarations for the return statement. Like with the type declaration for function arguments, by enabling the strict requirement, it will throw a «Fatal Error» on a type mismatch.
To declare a type for the function return, add a colon ( : ) and the type right before the opening curly ( < )bracket when declaring the function.
In the following example we specify the return type for the function:
Example
You can specify a different return type, than the argument types, but make sure the return is the correct type:
Example
Passing Arguments by Reference
In PHP, arguments are usually passed by value, which means that a copy of the value is used in the function and the variable that was passed into the function cannot be changed.
When a function argument is passed by reference, changes to the argument also change the variable that was passed in. To turn a function argument into a reference, the & operator is used:
Example
Use a pass-by-reference argument to update a variable: