What is function in PHP? :

A function is a way of wrapping up a portion of code and giving that code portion name, so that you can use that portion of code later in just one line of code. Functions are most useful when you will be using the same code at more than one place. Even they can be useful in one use situation as they make your code much more readable.

Syntax :

function function_name ($argument1, $argument2..)
{
          // statements ;
}

Function definition in PHP have four parts :

  • The special word function.
  • The name of the function. (A valid function name starts with a letter or underscore.)
  • He function’s parameter list : dollar sign variable separate by commas.
  • The function body – a brace enclosed set of statements.

Example :
<?php
function add()
{
$X = 10;
$Y = 20;
SUM = $X + $Y;
echo “<br> SUM is : ” , $SUM ;
}
add();
?>

functions_php

Function with Arguments :

Information may be passed to functions via the argument list which is a coma delimited list of expressions.
PHP supports passing arguments by value (the default) , passing by reference and default argument values.

Example :
<?php
function add($A , $B)
{
SUM = $A + $B;
echo “<br> SUM is : ” , $SUM ;
}
add(40 , 45);
?>

Functions_with_arguments

Function with Return :
You can return the value from function.

Example :
<?php
function add($A , $B)
{
SUM = $A + $B;
}
add(4 , 45);
echo “Sum  is : ” , $SUM ;
echo “<br> Sum is : ” ,add(10 , 15) ;
?>

functions_with_return

Function arguments passed by reference :
By default function arguments are passed by value but if you wish to allow a function to modify its arguments, you must pass them by reference.

If you want an argument to a function to always be passed by reference, you can prepend an ampersand (&) to the argument name in the function definition.

Example :
<?php
function show(& $B)
{
$B ++;
echo $B ;
}
$A = 5;
show($A);
?>

Reference in PHP

Function with default argument :

You can define an argument as having a default value. If you don’t pass argument it will take default values.

Example :
<?php
function sub($A = 20 , $B = 15)
{
echo “<br>Subtraction is  : ” , $A – $B ;
}
sub();
sub(10);
sub(25, 16);
?>

function_default argument