Function in PHP

Function in PHP-

PHP functions are similar to other programming languages. A function is a piece of code that takes one more input in the form of parameter and does some processing and returns a value. Functions are blocks of code that perform specific tasks.Built-in functions are functions that are defined with PHP. PHP has more than 1000 built-in functions, and also you can customize functions. In this tutorial we will see how to create the custom function in PHP.

Creating a PHP Function

A user-defined function declaration starts with the word function. A function name must start with a letter or an underscore. Function names are not case-sensitive. Function can take zero or any number of arguments.
A function is defined using following :

<?php
function function_name($arg_1, $arg_2, /* ..., */ $arg_n)
{
/* Function Body */
return $retval;
}
?>

Example :

<?php
function demo() {
echo "Hello world!";
}
?>

In the above example , we create a function named “demo()”. The opening curly brace ” { ”  indicates the beginning of the function code, and the closing curly brace “}”  indicates the end of the function. The function outputs “Hello world!”.

Calling the Function

To call the function, just write its name followed by brackets ().

<?php
function demo() {
echo "Hello world!";
}

demo(); // call the function
?>

PHP Functions returning value

A function can return a value using the return statement in conjunction with a value or object. return stops the execution of the function and sends the value back to the calling code. You can return more than one value from a function using return array(val1, val2, val3, val4).

<?php
function add($num1, $num2) {
$sum = $num1 + $num2;
return $sum;
}
$addition = add(10, 20);

echo "Returned value from the function : $addition";
?>

Dynamic Function Calls

In PHP we can assign function names as strings to variables and then treat these variables exactly as you would the function name itself.

Example:

 <?php
function demo() {
echo "Hello World";
}

$function_name = "demo";
$function_name();
?>

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.