You are on page 1of 3

Functions in PHP

Definition:

Functions are a block of code wrapped inside the {} brackets indicating beginning
and end of the function code.

Advantages of using functions are:


1) Better Organization of code
2) Easy to debug
3) Reusability
4) Easy maintenance.

In php we have two types of functions

1) Built-in function(string functions (strlen, strcmp,strrev), numeric


functions(rand(),is_number(),sqrt(), date function date())

2) User define functions

Rules

Rules that must follow when creating our own functions.


 Function names must start with a letter or an underscore but not a number
 The function name must be unique
 The function name must not contain spaces
 It is considered a good practice to use descriptive function names.
 Functions can optionally accept parameters and return values too.

Creating functions in PHP

1) To create a function in php we use function keyword

Syntax:
function function_name( ) // Defining a PHP function
{
Statements;

Sonali Yadav Date: 25/03/2020 UNIT-3


}
function_name( ); //Calling a PHP function

Example1: Function without parameters


<?php
function hello()
{
echo "Good morning Every One";
}
hello();
?>

Example2: Function with parameters and no return value


<?php
function add($num1,$num2)
{
echo $num1+$num2;
}
add(567,59);
?>
Example3: Function with parameters and return value
<?php
function multi($num1 , $num2)
{
$mul= $num1*$num2;
return $mul;
}
$return_value = multi(10,20);
echo $return_value;
?>

Sonali Yadav Date: 25/03/2020 UNIT-3


Passing Arguments by Reference

By default, value passed to the function is call by value. To pass value as a


reference, we need to use ampersand (&) symbol before the argument name. Value
passed to the function doesn’t modify the actual value by default (call by value)
.But we can do so by passing value as a reference.
Example 4: Passing Arguments by Reference:
<?php
function add($num1) /Call by Value
{
$num1+=5;
echo "The value of num1 is::".$num1;
}
function sum(&$num1) //Call by reference
{
$num1+=5;
echo "The value of num1 is::".$num1;
}
$x=12;
add($x);
echo "<br><br>";
echo "The value of x is::".$x;
echo "<br><br>";
sum($x);
echo "<br><br>";
echo "The value of x is::".$x;
echo "<br><br>";
?>

Sonali Yadav Date: 25/03/2020 UNIT-3

You might also like