Function in PHP

In very simple language a function is a block of code that can be used to perform a specific task. In addition, we can use a function multiple times without writing it again and again. For example, you want to perform some mathematical task in your code several times. It means you have to write code several times to perform that mathematical task. But with the help of the function, you can write your mathematical task code only once and you can use it any number of times.

Advantage: –

Before digging deep into this topic. Here is a list of a few advantages of using functions in PHP.

  • Code Reusability: We can call a function any number of times after defining it once.
  • Less Code: When we use functions in code. It reduces the length of the overall code(program).
  • Easy to Understand: Because we separate different programming logics into different functions so it becomes so easy to understand and maintain the code.

Defining a Function in PHP: –

Let’s check how to make and call a function in PHP Program. To make a function just write the function name with () and then write the body of the function.

<?php
// Defining function
function hello(){
    echo "Hello World<br>";
}
// Calling function
hello();
hello();
?>

Output: –

Hello World
Hello World

After following the above Program example you would have a clear idea of how we can define and call a simple function in PHP. But do you know that we can also pass values to a function to perform some task? When we create(define) a function that can receive values this kind of function is known as Parameterised Function.

Function with Parameter:

Sometimes we need data to process in function. We can send data to a function while calling that function. Check the example below to understand it.

<?php
$name="Owlbuddy";
// Defining function
function hello($n){
    echo "Hello ".$n."<br>";
}
// Calling function
hello($name);
hello($name);
?>

Output:

Hello Owlbuddy
Hello Owlbuddy

 

Spread the love
Scroll to Top