PHP - Function
The real power of PHP comes from its functions. In PHP, there are more than 700 built-in functions. In this chapter we will show you how to create your own functions.
To keep the script from being executed when the page loads, you can put it into a function.
A function will be executed by a call to the function.
You may call a function from anywhere within a page.
A function will be executed by a call to the function.
PHP Function Syntax
function functionName()
{
code to be executed;
}
PHP function guidelines:
- Give the function a name that reflects what the function does
- The function name can start with a letter or underscore (not a number)
PHP Function Example
A simple function that writes my name when it is called:
<html>
<body>
<?php
function writeName()
{
echo "Mr. Nice Guy";
}
echo "My name is ";
writeName();
?>
</body>
</html>
PHP Function Output
My name is Mr. Nice Guy
To add more functionality to a function, we can add parameters. A parameter is just like a variable. Parameters are specified after the function name, inside the parentheses.
The following example will write different first names, but equal last name:
<html>
<body>
<?php
function writeName($fname)
{
echo $fname . " Refsnes.<br />";
}
echo "My name is ";
writeName("Made d'Bali");
echo "My sister's name is ";
writeName("Ida Ayu Komang");
echo "My brother's name is ";
writeName("Kolang Kaling");
?>
</body>
</html>
Adding Parameters Output:
My name is Made d'Bali.
My sister's name is Ida Ayu Komang.
My brother's name is Kolang Kaling.
The following function has two parameters:
<html>
<body>
<?php
function writeName($fname,$lname)
{
echo "Gusti ".$fname." Oka ".$lname."<br />";
}
echo "My name is ";
writeName("Putu","Dayendra");
echo "My sister's name is ";
writeName("Made","Larasati");
echo "My brother's name is ";
writeName("Nyoman","Sanjaya");
?>
</body>
</html>
Output:
My name is Gusti Putu Oka Dayendra.
My sister's name is Gusti Made Larasati.
My brother's name is Gusti Nyoman Oka Sanjaya.
To let a function return a value, use the return statement.
PHP Return Value Example
<html>
<body>
<?php
function add($x,$y)
{
$total=$x+$y;
return $total;
}
echo "1 + 16 = " . add(1,16);
?>
</body>
</html>
PHP Return Values Output:
1 + 16 = 17