BreadcrumbHomeResourcesBlog What Is a PHP Function? January 30, 2020 What Is a PHP Function?PHP DevelopmentBy Maurice KherlakianFunctions are an essential building block in PHP, enabling developers to write clean, efficient, and reusable code. They simplify complex tasks by breaking them into manageable pieces, making applications easier to develop and maintain.In this blog, we break down what a PHP function is, how many PHP functions there are, and share PHP function examples.Table of ContentsPHP Functions: Frequently Asked QuestionsPHP Function ExamplesPHP Function Example: New Anonymous Function Syntax in PHP 7.4PHP Functions and Methods: What's the Difference?Final ThoughtsAdditional ResourcesTable of Contents1 - PHP Functions: Frequently Asked Questions2 - PHP Function Examples3 - PHP Function Example: New Anonymous Function Syntax in PHP 7.44 - PHP Functions and Methods: What's the Difference?5 - Final Thoughts6 - Additional ResourcesBack to topPHP Functions: Frequently Asked QuestionsWhat Are PHP Functions?PHP functions provide code that a PHP script can call to perform a task.These include examples 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.What Role Do PHP Functions Play in Development?The use of PHP functions streamlines development by:Establishing a modular development approachProviding logic that is reusable by other PHP applicationsNegating the necessity to re-develop and re-write the same logic over and over againWhat Are the Two Types of Functions in PHP?The two types of functions in PHP are built-in functions and user-defined functions.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 PHP function is built-in or user-defined, the following requirements must be met:Calling functions must always start with the keyword functionPHP 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 sensitiveHow 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 topPHP Function ExamplesWith so many PHP function examples available, we certainly don't have time to cover them all in a single blog. In this section, I will provide a few common PHP function examples, including code.Definitions and AttributesWith the above definition in place, let's take a look at some function definitions and attributes: <?php 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 PHP 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.) Optional ArgumentsLet's take a look at an example of a PHP function with optional arguments:<?php function optionalDemo($greeting, $count = 1) { for ($i = 0; $i < $count; $i++) { echo $greeting. "\n"; } } optionalDemo("Hello"); 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.Variable ScopingWhen learning about PHP 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; scopedemo($fruit); 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.Variables as ReferenceFinally, 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.RecursionA 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)); } }Anonymous FunctionsThe 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:function($number) { 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.Back to topPHP Function Example: New Anonymous Function Syntax in PHP 7.4PHP 7.4 (now end of life) 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 topPHP 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"); $mustang->printMake(); $camaro = new car("Chevrolet", "Camaro"); $camaro->printMake(); /* Ford Chevrolet */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 topFinal ThoughtsPHP functions are a fundamental aspect of the language, empowering developers to create efficient, modular, and reusable code. Their versatility and varied use cases make them indispensable tools in both procedural and object-oriented programming. By mastering PHP functions, developers can simplify complex tasks, enhance maintainability, and build more robust and scalable applications.Secure and Supported ZendPHP RuntimesTake advantage of backported security patches and dedicated 24/7/365 support with Zend PHP runtimes. Add the ZendHQ extension to unlock unparalled observability tooling.About ZendPHP Free ZendPHP+ZendHQ TrialBack to topAdditional ResourcesTraining - Free Training Course: Installing PHPTraining - Free Training Course: PHP BasicsTraining - Free Training Course: Interactive Web FormsBlog - PHP Development: Using PHP ExtensionsBlog - What Is a Foreign Function Interface in PHP?Back to top