What is PHP Function?

PHP functions are a block of code that you can use many times without writing again and again. There are many PHP built-in functions like PHP implode, PHP explode and PHP date that you can use in your code.

However, you can create your own function which can perform some specific task as per your need. These functions are user-defined functions which you can learn here to create them and use in your code.

How to Create a User-defined PHP Function?

You can create a user-defined PHP function easily by using the below-given syntax.

Syntax

To declare a function you need to start it with the name “function” followed by the name of the function.

If you want to use a function in your code, you need to first create that function and then after calling the function where you want to execute the code you entered inside the function.

You don’t need to repeat the block of code again and again. Just write a function and include the code. Use the function many times as per your need.

The name of the function must start with a letter or underscore not with a number. Also, remember that function names are not case-sensitive.

Call By Reference in PHP Function

By default, the function does not modify the actual value passed to a function. However, we can do so by passing the value by reference.

To do so, you have to use the ampersand(&) symbol before the argument name you pass to a function.

Below is the simple example you can check to understand the concept.

Output

10
20

Default Argument Value in PHP Function

When you use the default value for a function, you don’t need to specify any argument for them when you want to call it. The output will take the default value as the reference value for a function.

check out the below given simple example to understand the concept.

Output

Virat scored 50 many times in one day matches.
Virat scored 100 many times in one day matches.
Virat scored 150 many times in one day matches.
Virat scored 200 many times in one day matches.

Returning Value From a PHP Function

You can return the value by using the return statement inside any function. Use the return string followed by the variable you want to return.

Output

The score is 100

You must read:-

Reference

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.