Function
What is Function?.

Function is just like container for script. In Function we write script. When we call function then store script will run. Once you have to create function. You can call this function anywhere in Programme. If We are not use function then we write script again and again. Function has generally two type:

Library Function:-
This is already built in PHP. We just call it . For Library Function read PHP Reference.
User Define Function:-
This is create by Programmer. Means Programmer self create function then call it.

User Define Function.

This is create by Programmer. Means Programmer self write script into function.

Syntax:-

function functionname()
{
write code here;
}

How to call Function:-

functionname(argument);

Example 1:- Example to Create Function and Call function

<?php
function show()
{
echo “Welcome User”;
}
show();
?>

Output:-
Welcome User

Example 2:-Example for Passing Parameter into Function. Note:- Parameter is just like variable. Like $name is parameter into function

<?php

function show($name)
{
echo "Your Name :".$name;
}
show("John");

?>

Output:-
Your Name: John

Example 3:-

Example for Passing Parameter into Function and returning value from Function
Note:- return Means return any variable data from function.

<?php
function add($x,$y)
{
$result=$x+$y;
return $result;
}
echo add(10,16);
?>

Output:-
Your Name: 26

Example 4:-

use of function with form tag.

<?php
if(isset($_POST['btnsubmit']))
{
$number=$_POST['num'];
function positive($number)
{
if($number>0)
echo "positive";
else
echo "Negative";
}
positive($number);
}
?>
<html>
<head>
<title>Function</title>
</head>
<body>
<form name="frm" action="" method="post">
Enter Number<input name="num" type="text" /><br />
<input name="btnsubmit" type="submit" value="Submit" />
</form>
</body>
</html>

When User input any positive number like user input 5 then
Output:-
Positive

Call by Value

<?php
function add($a,$b)
{
return $a+$b;
}

$x=6;
$y=9;

echo add($x,$y);
?>

Call by Reference

<?php
function add(&$a,&$b)
{
return $a+$b;
}

$x=6;
$y=9;

echo add($x,$y);
?>

Function with default parameter

<?php
function add($a,$b=4)
{
return $a+$b;
}

$x=6;

echo add($x);
?>


Previous
Next