In PHP, more than 700 built-in functions are provided.
PHP functions
In this tutorial, we'll explain how to create your own functions.
For references and examples of built-in functions, please visit our PHP reference manual.
Creating PHP Functions
A function is a block of code that can be executed whenever it is needed.
To create a PHP function:
All functions start with the keyword function ()
Named function-the name of the function should indicate its function. The function name begins with a letter or an underscore.
The part of adding "{"-the curly braces for openings is the code for the function.
Insert Function code
Add an "}"-function ends by closing curly braces.
Example
A simple function that outputs my name when it is invoked:
<html>
<body>
<?php
function Writemyname ()
{
echo "David Yang";
}
Writemyname ();
?>
</body>
</html> using PHP functions
Now we're going to use this function in the PHP script:
<html>
<body>
<?php
function Writemyname ()
{
echo "David Yang";
}
echo "Hello world!<br/>";
echo "My name is";
Writemyname ();
echo ". <br/>that ' s right,";
Writemyname ();
echo "is my name."
?>
</body>
</html> the output of the above code:
Hello world!
My name is David Yang.
That's right, the David Yang was my name.
PHP functions-Add parameters
Our first function is a very simple function. It can only output a static string.
By adding parameters, we add more functionality to the function. parameter is similar to a variable.
You may notice that the function name is followed by a bracket, such as writemyname (). Parameters are specified in parentheses.
Example 1
The following example tells the output of a different name, but the last name is the same:
<html>
<body>
<?php
function Writemyname ($fname)
{
Echo $fname. "Yang.<br/>";
}
echo "My name is";
Writemyname ("David");
echo "My name is";
Writemyname ("Mike");
echo "My name is";
Writemyname ("John");
?>
</body>
The output of the code above </html>:
My name is David Yang.
My name is Mike Yang.
My name is John Yang.
Example 2
The following function has two parameters:
<html>
<body>
<?php
function Writemyname ($fname, $punctuation)
{
Echo $fname. "Yang". $punctuation. "<br/>";
}
echo "My name is";
Writemyname ("David", ".");
echo "My name is";
Writemyname ("Mike", "!");
echo "My name is";
Writemyname ("John", "...");
?>
</body>
The output of the code above </html>:
My name is David Yang.
My name is Mike yang!
My name is John Yang ...
PHP Function-return value
Function can also be used for return values.
Example
<html>
<body>
<?php
function Add ($x, $y)
{
$total = $x + $y;
return $total;
}
echo "1 + 16 =". Add (1,16);
?>
</body>
</html> the output of the above code:
1 + 16 = 17