# Functions

0 ricky158987873 December 8, 2020

The functions are defined as a self-contained block of statements that perform a particular task or job. This is a logical unit that composes a number of statements group into a single unit. It is often defined as a section of a program performing a specific job. Each program has one or more functions.

We have many advantages in using function.

• Manageability
• Code Reusability
• Non-redundant (non-repeated) programming (i.e. avoids redundant programming)
• Logical Clarity
• Easy to divide the work into many different programmers

The syntax of the function is:

``````function_name (parameter_list)
{
//Statement(s)
}``````

Let’s take an example to make clear concepts on function.

``````<?php

function sum(\$a, \$b)
{
return \$a + \$b;
}

echo "Sum of 5 + 6 = ".sum(5, 6);
echo "Sum of 5 + 10 = ".sum(5, 10);

?>``````

The output of the above program is:

``````Sum of 5 + 6 = 11
Sum of 10 + 5 = 15``````

In this example, a function sum() defines once and it is called two times to calculate the sum of two numbers. The detail of the defining function will discuss later in this chapter.

## Types of Function

We have two types of functions in the PHP programming language.

### 1. Built-in Function

There are the functions that are already written, compiled, and placed in PHP library and they are not required to be written by a programmer. The function’s name, its return type, their argument number, and types have been already defined. We can use these functions as required. For example printf()scanf()etc are the example of library functions.

Let’s look at one example to make clear concepts on built-in function.

``````<?php

/**
* Calling built-in function
* strtoupper()
* We are directly calling this function
*
*/
\$str = "Welcome to Code Help Pro";
echo strtoupper(\$str);

?>``````

The output of the above program is:

``WELCOME TO CODE HELP PRO``

In the above program, We have used the strtoupper() function already exists in PHP library. This function helps us to convert all the strings to uppercase.

## User-defined Function

There are functions that is define by the user at the time of writing a program. the user has the choice to choose its name, return type, arguments, and types. In the above example, the function sum() is a user-define function

A complex program can be divided into a number of user-defined functions.

Let’s look at an example to make clear concepts on user-defined function.

``````<?php

function hello_world()
{
echo "Hello World";
}
hello_world();

?>``````

The output of the above program is:

``Hello World``