What Is a PHP Function?
January 30, 2020

What Is A PHP Function?

PHP Development

It's important to know PHP functions. Here, we break down what a PHP function is, how many PHP functions there are, and share PHP function examples.

Back to top

What Is A PHP Function?

A PHP function provides code that a PHP script can call to perform a task, such as Count(), file_get_contents(), and header(). The PHP language supports both procedural and object-oriented programming paradigms. In the procedural space, functions are a key building-block for developing and maintaining streamlined applications.

Back to top

What Role Do PHP Functions Play in Development?

The use of functions helps streamline development by:

  • Establishing a modular development approach.
  • Providing logic that is reusable by other PHP applications. 
  • Negating the necessity to re-develop and re-write the same logic over and over again.

Functions in PHP can be built-in or user defined:

  • Built-in PHP functions ship with PHP runtimes and their extensions — and they can be called from anywhere in a script (for example, print(), var_dump(), mysql_connect(), etc.).
  • User-defined functions are custom functions that developers create. 

Regardless of whether a function is built-in or user-defined:

  • Calling functions must always start with the keyword function.
  • PHP code must be contained within curly brackets {}.
  • Functions can be called by name, followed by arguments within parentheses.
  • Function names must start with a letter or underscore — not a number. (Starting function names with an underscore is typically reserved for super global variables that contain information such as session and cookie data.) 
  • Their names are not case sensitive.
Back to top

How Many Functions Are in PHP?

PHP has over 700 functions you can use for various tasks. Keep reading to get some examples you can use.

Back to top

What Are PHP Function Examples?

Here are some examples of PHP functions, including code. 

PHP Function Example: Definitions and Attributes

With the above definition in place, let's take a look at some function definitions and attributes: 

function x5($number)
	return($number * 5);
$multiple_number = x5(10);	// 50

The above is a complete PHP script, albeit a short and simple one. This particular function is simply returning the value that the function was called with, multiplied by five. Outside of the function definition we see a call to the function. The function is called simply by referencing the function and then providing the arguments to the function within parenthesis. 

The function keyword begins the definition of a function. In this case, the function name is x5. The variables in parenthesis indicate arguments for the function and how they will be referenced within the function. In this case, there is one function that will be referenced through the $number variable within the function. (We will talk about optional arguments, as well as variable scoping, later in this blog.) 

PHP Function Example: Optional Arguments

Let's take a look at an example of a PHP function with optional arguments:

	function optionalDemo($greeting, $count = 1)
		for ($i = 0; $i < $count; $i++)
			echo $greeting. "\n";
optionalDemo("Good Bye" , 2);

Like the previous example, the above is a complete code segment. The statement to focus on here is the functiondefinition. Notice that this function is expecting two arguments, which will be referenced as $greeting and $countwithin the function. Additionally, notice that the second parameter, $count, has a default value of '1' assigned. The way this works is that if the function is called with a single parameter (like in the first call to the function), then the default value of '1' will be assigned to the second parameter. This, in turn, will cause the ‘for’ loop within the function to be executed once. 

In the second call to optionalDemo, two values are being provided. Therefore, the value provided in the call is used for the second argument ($count) rather than the default value within the function definition. The result of this is that the loop within the function is executed twice.

PHP Function Example: Variable Scoping

When learning about functions, it is important to understand the concept of variable scoping. Put simply, the default behavior of variable scoping is for variables to be scoped to the function in which they are defined. Again, an example is the best way to demonstrate:

function scopedemo($fruit)
	$fruit = 20;
	echo $fruit;			// 20

$fruit = 10;
echo $fruit;				//10

This example shows the function definition as well as a call to the function. The thing to note is that a variable named $fruit is used both within and outside of the function, leading you to believe that it represents the same value (for example, the same memory space) — but it does not. 

As the comments in the code above show, $fruit within the function represents a different value/memory-space than $fruit outside of the function. If you want to access the same value/memory-space inside and outside a function, the global keyword can be used. 

Looking at the above example, if the statement global $fruit had been added to the function definition, then the references to it inside the function would be the same value or memory-space outside of the function. So, in this case, $fruit at the bottom of the code sample would have the value of 20. 

More information on variable scoping can be found on the PHP website.

PHP Function Example: Variables as Reference

Finally, variables can be passed as reference. Passing by reference causes a new entry to be added to the PHP symbol table which references an internal data structure that contains the variable type and value.  Consider the above example one last time. If the call to scopedemo had used an ampersand in front of the variable (for example, scopedemo (&$fruit)), then within the function, a new entry would have been added to the symbol table for the same data structure representing the variables value. This, in effect, scopes the variable both within and outside of the function.

PHP Function Example: Recursion

A slightly more advanced attribute of functions is recursion. Recursion is when a function is written so it can call itself. A recursive function must contain an end condition, which will cause the function to terminate.

Typically, when writing a recursive function there will be a 'base case' that is tested for within the function, and the function will continue to call itself until the 'base case' is satisfied. Examples of recursive functions include calculating factorials and reading a tree of files and/or directories. Here's what an example of what the code would look like:

function factorial($n) { 

    if ($n < 2) {
        return 1; 
    } else { 
        return ($n * factorial($n - 1)); 

PHP Function Example: Anonymous Functions

The last attribute we’ll look at is the anonymous function. While the definition of an anonymous function is the same as a user-defined function — namely that it accepts arguments, works with variables, and contains code logic) — the function has no name and ends with a semicolon. This is because unlike regular functions, which are code constructions, an anonymous function is an expression. 

Consider an earlier example, which I code here as an anonymous function:

	return($number * 5);

This anonymous function code can never be called. The semicolon at the end of the function definition ensures that the function is treated as an expression. Since it is treated as an expression, it can be assigned to a variable, allowing it to be called by referencing the variable. It can also be passed to another function, which makes the anonymous function a callback. 

Another point to make about anonymous functions is that they can be returned from another function. This is referred to as a closure.

PHP Function Example: New Anonymous Function Syntax in PHP 7.4

The latest version of PHP, 7.4, introduced a new syntax for anonymous functions:

$double = fn($param1) => 2*$param1;

The use of the arrow function (=>) allows a short closure to be used for creating one-line functions. This is helpful in writing tighter code.

Also notice that the return keyword is not necessary for single expressions. The value of that expression (2*$param1in the above example) is returned.

Anonymous functions are most useful as the value of callback parameters, but they have other use cases. They are throw-away functions when you need a function that you want to only use once. 

Back to top

PHP Functions and Methods: What's the Difference?

At the beginning of this blog, I mentioned that in the procedural world of PHP, functions are similar to what object-oriented developers call methods. Let’s look at one final example: 

class car 
public $make;
private $model;
function __construct($make, $model) 

$this->make = $make;
$this->model = $model; 

function printMake() 

echo $this->make . "\n"; 

$mustang = new car("Ford", "Mustang");
$camaro = new car("Chevrolet", "Camaro");

Look at the highlighted portion of the above code. Notice that even though we are in a class definition, the keyword function defines what object-oriented developers call a method. So really, method can be another name for a function. 

Like functions, methods can work with arguments and contain blocks of code. 

However, in the object-oriented world:

  • Methods work with values that are contained within a copy of the class (referred to as an object).
  • In a method, there can be multiple iterations of the same class definition in different variables (or even arrays of objects). 

The takeaway here is that the method definition follows the same format as the function definition discussed throughout this blog.

Back to top

Use PHP Functions and More With Zend

Learning PHP functions is just the beginning of mastering PHP development. If you want to truly master PHP development, it's a good idea get PHP training and a PHP certification.

You'll also want to consider your PHP toolset — including your server.

Develop in PHP With With Zend Server

Zend Server is your all-in-one PHP application server. Use it to improve PHP web application deployment, debugging, and monitoring. 

See for yourself how Zend Server can help you — and your team — move faster. Get started with a free 30-day trial. 

Try Zend Server


Additional Resources

Back to top