- Functions in PHP Tutorial
- Functions
- How to define a function
- How to call (invoke) a function
- How to define a function with arguments
- 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
- Functions in PHP: Return Values and Parameters
- Internal Functions in PHP
- User-Defined Functions in PHP
Functions in PHP Tutorial
In this tutorial we learn about functions in PHP and how they help us break up our application logic into smaller sections for easy reuse throughout our code.
- Functions
- How to define a function
- How to call (invoke) a function
- How to define a function with arguments
- How to use optional (default) parameters
- How to use named parameters
- How to use variable parameter lists
- How to use variadic parameters
- How to call a function in a loop
- How to return a value from a function
- Function return types
- Callback functions
- Closures
- Arrow functions
Functions
As an application becomes bigger and more complex, we need ways to separate our code into smaller, reusable sections of logic. Functions are wrappers for those sections of logic.
But they’re not just wrappers, they allow us to interact with the code inside to make a section of logic as reusable as possible.
As an example, let’s consider the following code. It uses conditional control to evaluate if a number is even or odd.
""If we want to do the same evaluation on other numbers, we would have to rewrite the whole section of logic. To avoid this problem, we can wrap the logic inside a function.
note We’ve used some built-in PHP functions earlier in the tutorial course, like the array() function.
How to define a function
A function can be simple or complex, based on the logic it contains. We will start with a simple function definition and add to its functionality as we go along.
Functions in php consist of a minimum of 4 tokens.
- The function keyword.
- A descriptive identifier (name).
- A parameter list wrapped with () (open & close parentheses).
- A code block wrapped with <> (open & close curly braces).
Inside the code block is where we write our section of logic.
Functions are typically responsible only for a single task, which makes it easy to give them names. Our example below is responsible for alerting the user, so we can call it alertUser .
To keep things simple for the moment, the logic is just an echo statement. But we can have conditional statements, loops, even other functions inside.
How to call (invoke) a function
At this point our function is defined, but we haven’t actually used it yet. To use a function we call it, which will execute the logic in the code block.
To call a function all we need to do is reference the function name and the parameter list parentheses.
note Even though we don’t have any parameters in our function yet, we still have to write the parentheses when calling the function.
To demonstrate, let’s call the alertUser() function we defined earlier.
If we run the example above in the browser, it will display the message that’s defined in the function’s code block.
Once a function has been defined, we can use it anywhere in our script, even above the definition.
The only exception to this is when a function is defined conditionally.
Function names are case insensitive, but it’s good practice to always use the same case that the function was defined with.
We covered PHP's casing conventions earlier in the course.
Functions can be called as many times as we need.
Each time the function is called, it will execute its logic.
How to define a function with arguments
We know from using the array() function that we can pass some values to a function through its parameter list.
Parameters are temporary variables that we define and then use in the logic of the function’s code block. It’s similar to the temporary variable in a foreach loop.
To create parameters, we specify them in the parameter list (between parentheses) when we define the function. If we use more than one parameter, we separate them with a commas.
The parameters we define should be used somewhere in the logic. To demonstrate, let’s add a $user parameter to our function and use it in the echo statement.
The value (argument) we pass to the funtion when it’s called will replace all the instances of $user in the logic.
If a function contains a non-default parameter, we have to specify an argument for it when we call the function. Otherwise, the interpreter would raise an error.
Output: Missing argument error
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
?>?phpTo 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:
Functions in PHP: Return Values and Parameters
Monty Shokeen Last updated Feb 17, 2021
Functions are an important part of programming languages. They help us avoid code duplication by allowing us to run the same set of instructions over and over again on different data.
In this tutorial, we will talk about functions in PHP. We will cover all the basic concepts of functions in PHP, and you’ll learn how to create your own user-defined functions in PHP. You will learn about returning values from a function and function parameters in PHP. You’ll also learn other concepts like setting default argument values or passing an argument by reference.
Internal Functions in PHP
PHP comes with a lot of built-in functions that you can use in your program. Some of these functions come as standard, while others become available to you through specific PHP extensions.
PHP comes with a lot of functions to work with strings. For example, you can use the str_contains() function to check if a string contains a substring and the wordwrap() function to wrap a string to a given number of characters. These functions are available for you to use as standard.
Another set of PHP functions for manipulating images is available if you install the GD extension library. Once the extension is enabled, you will be able to use functions like imagecreatetruecolor() , imagecreatefrompng() , and imagefill() to create and manipulate images.
If you ever get a fatal undefined function error in PHP but you are certain that it is an internal function, make sure that you have installed the respective extensions to use that function.
User-Defined Functions in PHP
You can also define your own functions in PHP. Defining your own functions becomes a necessity in almost every non-trivial program you write. They are a great way to avoid code duplication and errors.
Here is some basic code to define a function that outputs a greeting when we call the function later.