go top

MEGA Sale

  • Colection of 65 PHP scripts for $4.29 each

Get 65 PHP scripts in a bundle for $4.29 each!

View Offer

List of PHP 8 Functions in 2021

by Administrator /  Useful Resources

Understanding PHP functions is an essential part of learning PHP. It’s one of the most powerful features the programming language has to offer. In the following guide, we will cover everything you need to know about functions in PHP 8.0 – the newest version to date. We'll find out how functions work, what you can use them for, and how to create your own.

What Are PHP Functions?

In programming, a function is basically a shorthand for a reusable piece of code that performs a specific task. If you assign a code snippet to a function, you can then execute the entire thing by only calling the function by its name, which is much faster and more convenient than typing out the code snippets every time.

Let’s go over the basic syntax of PHP functions to make this clearer. Here’s an example:

function example_function() {
    echo 'This is an example function.';
}

This function does a very simple thing. When executed, it will print "This is an example function." on screen.

In PHP, you can create a function, just like above, by using the function keyword, followed by the name you want to assign to the function. Whatever you place in between the curly brackets will be executed in your PHP document every time you include a call to the function.

In this case, the function call looks like this:

example_function()

Much shorter than the original, right?

The Benefits of PHP Functions

But why should you go through the trouble of defining functions in the first place, instead of simply using the PHP code on its own? Well, using functions offers two important benefits:

  • Simplification – One of the main benefits is that functions allow you to use the code snippets they contain wherever and however many times you want – simply call the function and that’s it. So, functions make coding much easier, compared to re-typing or copy-pasting the snippet itself, and they help reduce repetition. The function doesn’t even have to be in the same file, as long as you import its source.
  • Centralization – Imagine you discover that there is an error in a piece of code that you use a lot. If it’s placed inside a function, you only have to correct it once where the function is defined. On the other hand, when using the code snippet itself, you have to correct every single instance of it separately. Consequently, PHP functions make your code simpler to maintain and also make it easier to detect where exactly the error lies.

As you can see, there are some very good reasons to use functions over naked code. Next, let’s take a look at some more features and characteristics of PHP functions.

Types of PHP Functions

Several types of PHP functions exist. For example, below we’ll take a look at recursive functions. However, on the most basic level, there are only two main types: built-in PHP functions and user-defined functions.

Built-in Functions

The first type are functions that are baked into PHP. These include tools that let you work with and manipulate variables, arrays, and strings over date and time functions, functions to catch and display errors, and functions that allow you to access a MySQL database, and more.

They are available to every PHP user and can perform tasks like count the number of letters in a string or combine or split groups of variables. echo(), which we used in the example above, is also a function. Other examples include:

  • gettype() – Retrieves the type of a variable.
  • print_r() – Puts out information about a variable that is readable to humans.
  • var_dump() – Dumps information about a variable.

If you want to know more about built-in PHP functions, you can read about them in the PHP documentation. You can also find a collection of the most basic functions in our PHP cheat sheet.

User-Defined Functions

Luckily, you’re not limited only to the tools that are already inherent to PHP. If you need something tailor-made, it’s possible to easily create your own functions. In fact, if you’re using PHP to create websites, this is likely what you’ll spend a lot of your time doing.

If you have ever used a CMS like WordPress, you’ll know that it comes with a lot of its own, WordPress-specific functions. For example, you can use the_title() in your page templates to output the current post title.

However, this only works because the content of this function has been defined in wp-includes/post-template.php. When you take a look at that file, here’s what you’ll find:

function the_title( $before = '', $after = '', $echo = true ) {
    $title = get_the_title();
 
    if ( strlen( $title ) == 0 ) {
        return;
    }
 
    $title = $before . $title . $after;
 
    if ( $echo ) {
        echo $title;
    } else {
        return $title;
    }
}

You can only use this function in your files because the code snippet above exists. Since user-defined functions are such a crucial topic, the rest of this article will take a detailed look at how to create your own PHP functions.

How Do You Build Functions in PHP?

As seen above, this is the basic syntax for creating user-defined functions:

function function_name() {
    // code to execute goes here
}
function_name();

However, the devil is in the details, so let’s go over some of the finer points in more detail.

The Function Name

Let’s start with how to name your own functions. First of all, a function name needs to start with a letter or underscore and can not begin with a number. It’s customary to separate words with underscores (e.g. my_php_function()) though some people also use camelCase and PascalCase. Function names are also not case-sensitive, so writing My_PHP_Function() and my_php_function() doesn’t make a difference – it’s still the same function.

Aside from that, it’s a good idea to use a name that describes what your function does. This will make it much easier to understand for other people who read your code or even yourself if you come back to it after a long while. It’s a type of self-documentation.

Commonly, to achieve this, you will start the function name with a verb like remove_post_meta() or register_sidebar(). When working in an environment such as WordPress, which has a lot of built-in functions, it’s also common to start all your custom functions with an identifier like your initials, to avoid accidentally using an existing name. Here’s an example: xyz_register_sidebar().

Parameters and Arguments

You might have noticed the parentheses at the end of the function name, which seem to serve no purpose so far. As a matter of fact, they have a purpose – it’s where you can include parameters or arguments, which is something that PHP functions can contain. These are similar to variables and allow you to pass on and work with specific information.

Here’s how to use them:

function combine_strings($string1, $string2) {
    echo $string1 . ' ' . $string2;
}

When setting up your function, these are called parameters – the above example has two of them. Whatever two strings you put here at the function call, the function will combine them into a single sentence with a space in the middle.

When you use your own parameters in the function call, they are called arguments, however, they are essentially the same thing.

combine_strings('Hello', 'world!'); // output: "Hello world!"

In theory, you can use an unlimited number of parameters, you just have to separate them with commas.

Using Default Values

It’s also possible to set a default value for an argument. That way, when nothing is defined at the call of the function, it has something to fall back on. This can be useful to avoid throwing an error (if the function doesn’t work without an argument value) or when a certain value is usually the same.

We can create another example by slightly changing the function above:

function combine_strings($string1, $string2, $spacing = ' ') {
    echo $string1 . $spacing . $string2;
}
 
combine_strings('Hello', 'world!');

It’s basically the same as before and will produce the same output. However, in this case, we have replaced the single space from above with another parameter that now has the space as its default value, leading to the same output.

You might also notice that in the function call, we only input two parameters. This is fine in this case, because the third parameter ($spacing) already has a default value that the function will use if nothing else is defined in the call.

So, when you use default parameters, it's a good idea to place them after parameters that do not have default values (also known as required parameters). Otherwise, it can easily be confusing and cause uninteded behavior or errors. On top of that, since PHP 8.0, placing default parameters before required parameters will result in a deprecation error.

For example, the function below triggers a deprecation notice and causes a fatal error, because 'Hello!' and 'world!' correspond to parameters $spacing and $string1 while the third parameter ($string2, which is a required parameter) is not filled in at all when calling the function:

function combine_strings($spacing = ' ', $string1, $string2) {
    echo $string1 . $spacing . $string2;
}
 
combine_strings('Hello', 'world!');

PHP Type Hints

When you declare the parameters of a PHP function or define a variable, the programming language will usually figure out what type of data it contains by itself. You don’t have to explicitly say whether it’s a number/an integer, a string, or else. PHP will do the best with the information you provide it with.

However, you can also define the expected data type when declaring a function, using the strict keyword. That way, if the input doesn’t match, PHP will not try to “make it work” but instead will throw an error. This is how it works:

declare(strict_types=1);
 
function combine_strings(string $string1, string $string2, string $spacing = ' ') {
    echo $string1 . $spacing . $string2;
}
 
combine_strings('Hello', 5);

First of all, to use strict, you need to include declare(strict_types=1) at the top of your PHP file, otherwise it won’t have an effect. Secondly, notice that the function parameters are all prepended with string to tell the function that it should expect text here, not a number. Because the function call at the bottom says 5 as its second parameter, the above code will output an error.

You can also use strict to define the value type that a function will return. This is useful, for example, when calculating floats (numbers with decimal point) and you want the function to return integers (whole numbers). More on returning values below.

Named Arguments

Since version 8.0, PHP allows you to use named arguments for functions. They allow you to use arguments depending on their names, not just the order that they’re presented in.

Using the example from before, you can eliminate potential pitfalls by simply using argument names in the function call.

function combine_strings($string1, $string2, $spacing = ' ') {
    echo $string1 . $spacing . $string2;
}
 
combine_strings(
    $string1 = 'Hello',
    $string2 = 'world!'
);

Note that it doesn’t make any difference in which order you use the argument names in the function call – using names creates the correct output either way. In addition, pay attention to how we didn’t specify $spacing. That’s because it already has a default value, in which case you can skip it.

It’s also possible to use positional arguments together with named arguments. The only caveat here is that you need to place named arguments after positional ones, otherwise PHP will throw an error. The function call below will not work because the named arguments appear before the positional arguments.

combine_strings(
    $string2 = 'world!',
    'Hello'
);

Instead, the right way to call this function would be:

combine_strings(
    'Hello',
    $string2 = 'world!'
);

Passing Arguments by Reference

In the examples above, we have passed arguments by value, which is the default behavior in PHP. This basically means that a copy of the original value is passed through the function, but the original value, such as a variable you defined, remains untouched.

In contrast, you can also pass arguments by reference. In that case, the original value passes through the function and is altered by it. For this, you need to prepend the argument with an ampersand (&). Let’s take a look at an example where the function adds a string ($string1) to a defined value ($string2) when the function is called.

function combine_strings(&$string1) {
    $string1 .= ' and this is what gets added to it.';
}
 
$string2 = 'This is my original sentence';
 
combine_strings($string2);
 
echo $string2;

In this example, if you leave out the ampersand in front of the function parameter, the output will only be "This is my original sentence".

This is because the argument is altered outside of the function, namely at the function call (with the line combine_strings($string2);), which is why the originally defined function parameter ($string1 .= ' and this is what gets added to it.';) is overwritten. However, passing $string1 by reference prevents this, so if you add the & operator, the value that is already present in the function is preserved.

The return Statement

Using the return statement allows you to get PHP functions to return a value. That means, the value goes back to the part of the program that initially called it. The function will then contain the value so you can call and display it wherever you want.

Here’s what that looks like:

function combine_strings($string1, $string2, $spacing = ' ') {
    return $string1 . $spacing . $string2;
}
 
$variable = combine_strings('Hello', 'world!');
 
echo $variable;

Again, this is doing the same thing as we have done before (which is output "Hello world!"). However, in this case, we are combining the strings and storing them in the function. From there, you can echo the result whenever you want, instead of immediately and automatically at the function call.

The returned value may be of any type, including arrays and objects. The return statement also ends the function and stops it from executing further.

Using HTML in Functions

Although we are using PHP, it’s completely possible to use HTML inside functions. In fact, this happens a lot when you use WordPress or another CMS based on PHP. The programming language runs in the background, but when someone requests to see a page, it generates HTML that the browser can read.

Here is an example of what that might look like:

function combine_strings($string1, $string2, $spacing = ' ') {
    echo '<h1>' . $string1 . $spacing . $string2 . '</h1>';
}
 
combine_strings('Hello', 'world!');

Above, we have our familiar example, only this time the string output is additional wrapped into <h1> brackets. As a result, the web page will display "Hello world!" as the H1 heading.

Variable Scope: Local and Global Variables

While not directly related to PHP functions, variable scope is something that is relevant to this topic. Scope is basically the context in which a variable is available, which can either be local or global.

All variables that you define solely inside a function are automatically local and can only be used within that function.

function combine_strings() {
    $string1 = 'Hello';
    $spacing = ' ';
    $string2 = 'world!';
 
    echo $string1 . $spacing . $string2;
}
 
combine_strings();

In the above example, $string1$spacing, and $string2 all have local scope because they have been defined inside the function.

On the other hand, variables defined outside of functions are global which means you can’t simply access them from inside functions either. For example, this won’t work:

$string1 = 'Hello';
$spacing = ' ';
$string2 = 'world!';
 
function combine_strings() {
    echo $string1 . $spacing . $string2;
}
 
combine_strings();

Even though it looks like it should, the above snippet will produce an "Undefined variable" error because the variables aren’t defined inside the function.

In addition, the following piece of code will still output "Hello world!" despite the function variables saying something else:

$string1 = 'Hello';
$spacing = ' ';
$string2 = 'world!';
 
function combine_strings() {
    $string1 = 'Hi';
    $spacing = ' ';
    $string2 = 'globe!';
}
 
combine_strings();
 
echo $string1 . $spacing . $string2;

Although the variables have the same names, because one group of them is global in scope and the other is local, they are treated as different variables. This is so that there isn’t any confusion between variables that would generate errors.

However, if you want to use global variables within a function, you can do so by prepending them with the global keyword. This makes the externally defined variable available inside the function.

$string1 = 'Hello';
$spacing = ' ';
$string2 = 'world!';
 
function combine_strings() {
    global $string1;
    global $spacing;
    global $string2;
    echo $string1 . $spacing . $string2;
}
 
combine_strings();

There are also some built-in PHP variables called superglobals, which are accessible from anywhere. A few examples include $GLOBALS$_SERVER, and $_GET. They allow you to retrieve data from across different files, the user browser, and more. For the purposes of this post, we won’t delve into those because that’s a whole topic on its own. More on that in the documentation.

Recursive Functions

The final thing we want to go over are recursive functions. These get their name from the fact that they call themselves over and over until a certain condition is satisfied.

They are a little similar to loops. However, recursive functions are usually used for shorter blocks of code and loops for cases where you need larger code snippets.

Below is a simple function to print "Hello world!" a defined number of times (as defined by $greetings). The function will repeat until it has reached that number.

function combine_strings($greetings){
 
    $string1 = 'Hello';
    $spacing = ' ';
    $string2 = 'world!';
 
    if ($greetings >= 1) {
        echo $string1 . $spacing . $string2 . '<br>';
        combine_strings($greetings - 1);
    }
}
 
combine_strings(8);

Final Thoughts: PHP Functions

PHP functions are something you definitely need to get familiar with if you want to get proficient at this programming language. It opens up wide possibilities to create functionality and write more powerful code.

PHP already contains a plethora of built-in functions that you can use for this purpose. The real magic, however, happens when you learn to create your own custom functions. It opens up much larger possibilities and lets you truly use the power of PHP.

Above, you have learned all you need to make that happen – now it’s up to you to make use of it.

What’s your favorite feature of PHP functions? Anything to add to the above? Let us know in the comments!

Share on:

2 Comments to "List of PHP 8 Functions in 2021"

cbd gummies

cbd gummies / March 10, 2024 at 18:02 pm

I gave cbd products a try for the cardinal time, and I'm amazed! They tasted excessive and provided a be under the impression that of calmness and relaxation. My lay stress melted away, and I slept less ill too. These gummies are a game-changer on the side of me, and I greatly endorse them to anyone seeking spontaneous emphasis relief and better sleep.

John

John / December 14, 2022 at 13:18 pm

As with any newer version, PHP 8.0 has improved performance over PHP 7.4, but the biggest improvements come with additions like the Just-In-Time (JIT) compiler. JIT is an extension for PHP 8.0 that increases the speed of applications by how it handles the compilation of PHP scripts.

PHP development company are taking better use of PHP 8 version also developers are very happy with this new update.

Add your comment

Captcha

    Please, be polite and helpful and do not spam or offend others! We promise you will be treated the same way!

    Log in to your account to post your comments. If you still haven't joined our community yet, you can create your FREE account now!

    Posting tip:
    If you use code in your comments, please put it in these tags [php], [sql], [css], [js] PHP code example: [php] echo date("Y-m-d"); [/php]

    Thank you,
    PHPJabbers Team