PHP Functions

In this PHP tutorial, we are gonna learn about PHP functions, creating PHP functions, types of PHP functions and how to add two numbers using function in PHP.

A function is a block of code which is executable and performs a certain task.

Generally, functions are used to break a large code into small blocks.

PHP Functions:

In creating a large program with a huge set of programs the whole code becomes clumsy and which makes it look like a big mystery instead of having simple code. To solve this problem we use functions concept.

Create PHP function with optional parameter or argument

It is also in programs where we have to perform certain functionality repeatedly instead of writing the code for that many times we can simply create a function and store the code and call the function. It reduces both lines of code and time.

In PHP functions are of 2 types.

  1. Pre-Defined Functions
  2. User-Defined Functions

PHP Pre-Defined Functions:

These are the in-built functions which are already defined in PHP.

This provides the basic functionality for PHP.

Example: any( ), bin( ).

PHP User-defined Functions:

These are the functions which user built to use them in their programs.

We can also pass arguments to the function.

function function_name()

To pass parameters to functions we just pass them in ( ) after the function name.

function function_name(parameter1,parameter2...)

PHP function to add two numbers

We are going to add 2 numbers using a function named as add.


//creating a function
function add($a,$b)
echo $c;

echo "sum of 2  numbers is";

//calling a function

add(1, 2);

Explanation of the above Example.
  1. Here we create a function named add.
  2. Pass values of 2 variables a and b.
  3. Add them and print the value.
  4. Now in the main function call the add function and pass values.

*We can call a function in PHP once after it is created. So declare the function at the top of the code.

You can also check PHP program to check whether a given number is prime or not

Leave a Reply
