Functions in PHP

By | April 6, 2020

In this tutorial, we will learn about Functions in PHP. The function is a block of code which perform a specific task and which we can use 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 by using the function you have to write your mathematical task code only once and you can use it any number of times.

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

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

Function with Parameter:

In the last example, we learned how to define and call a function in PHP. Here we will learn how to define and call functions with parameters. Sometimes we need data to process in function. We can send data to function while calling that functions. Check the example below to understand it.

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