Functions –
Introduction
Functions are the real strength of PHP. There are
more than 700 built-in functions in PHP. You can also define them explicitly
based on your custom requirements. Functions are executed by calling the
functions and they can be called from anywhere in the program.
Writing
Functions
- Functions with zero Arguments
- Functions with Arguments
- Functions with default argument values
- Functions with return values
- Functions with zero arguments take empty parenthesis.
Example
<?php
echo "My location is ";
location();
function
location () // function name
{
echo
"Switzerland";
}
?>
Functions with
Arguments
·
We can pass
information to the functions through arguments.
·
Arguments are
supplied to the function within the parenthesis after the function name.
·
We can pass as
many arguments to the function by a comma separated list.
Example:
<?php
function name($fname,$lname)
{
echo
"first name is $fname.<br>";
echo
"last name is $lname<br>";
}
name("suhas","babu");
name("vinay","kumar");
name("vamsi","Krishna");
?>
Functions with
default argument values
Function without arguments uses the default argument
values. The following example shows the usage of default arguments:
Example
<?php
function setValue($v=10)
{
echo
" v value is $v";
}
setValue(20);
setValue();//uses the default argument value
?>
Functions with
return values
A Function uses the return statement to return the
resultant values. The following example explains the usage of return statement.
Example
<?php
function add($a,$b) {
$c=$a+$b;
return $c;
}
echo "the sum is” .add(10,10) . "<br>";
echo "the sum is ".add(10,100) .
"<br>";
?>