PHP Functions

PHP Functions

A function is a block of code to perform a specific task. This block of code can be executed anywhere in the program by calling it’s name. A simple syntax of PHP function is:

//define a function function f_name() {    block of code to perform a task; } //call a function f_name();

Let’s make a simple code to make our first PHP function.

<html> <body> <?php function first_func() {   echo "This is my first PHP function."; } first_func(); ?> </body> </html>

We have made a function named, first_func. First, a function is created by using the keyword, “function” which is followed by the function name. The function name should be self explanatory so that it is easy to use in the program. A function name should start with an alphabet or an underscore and should not contain special characters except underscore. All the code of the function should be within a pair of curly braces. The function once created can be used anywhere in the program by just mentioning the name of the function. In the above example, we have called the function, “first_func” in the program after creating it. Let’s see the output:

This is my first PHP function.

When a function is created, the code within it is not executed. The function is merely created. The code within the function will be executed only when it is called.


Adding parameters in PHP function

In the example above, there are empty brackets after the name of the function. These brackets are empty because we have not used any parameters in it. Parameters can be used along with a function when a variable has different values in the program. Let’s see with the help of an example how parameters are used in a PHP function.

<?php function add($x,$y) {    $sum=$x+$y;      echo "The addition of $x and $y is $sum."; } echo "The addition of 4 and 2 using add function:<br/>"; add(4,2); echo "<br/>The addition of 8 and 5 using add function:<br/>"; add(8,5); ?>

In the above example, we have called the function, “add” twice. The result will be:

The addition of 4 and 2 using add function: The addition of 4 and 2 is 6. The addition of 8 and 5 using add function: The addition of 8 and 5 is 13.

Return values in a PHP function

Till now we have seen that we call a function and it executes the code within it. But suppose that the output of the function has to be used outside the function. In this case, the function returns a value. Let’s see this with an example.

<?php function add($x,$y) {    $sum=$x+$y;      return $sum; } echo "The addition of 4 and 2 using add function:<br/>"; add(4,2); echo "<br/>The addition of 8 and 5 using add function:<br/>"; add(8,5); ?>

The output will be:

The addition of 4 and 2 using add function: 6 The addition of 8 and 5 using add function: 13
If you have found my website useful, please consider buying me a coffee below 😉