The real power of PHP comes from
its functions.
In PHP - there are more than 700
built-in functions available.
In this tutorial we will show you
how to create your own functions.
For a reference and examples of
the built-in functions, please visit our PHP Reference.
A function is a block of code that
can be executed whenever we need it.
Creating PHP functions:
A simple function that writes my
name when it is called:
<html> <body> <?php function writeMyName() { echo "Kai Jim Refsnes"; } writeMyName(); ?> </body> </html> |
Now we will use the function in a
PHP script:
<html> <body> <?php function writeMyName() { echo "Kai Jim Refsnes"; } 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 code above will
be:
Hello world! My name is Kai Jim Refsnes. That's right, Kai Jim Refsnes is my name. |
Our first function (writeMyName())
is a very simple function. It only writes a static string.
To add more functionality to a
function, we can add parameters. A parameter is just like a variable.
You may have noticed the
parentheses after the function name, like: writeMyName(). The parameters are
specified inside the parentheses.
The following example will write
different first names, but the same last name:
<html> <body> <?php function writeMyName($fname) { echo $fname . " Refsnes.<br />"; } echo "My name is "; writeMyName("Kai Jim"); echo "My name is "; writeMyName("Hege"); echo "My name is "; writeMyName("Stale"); ?> </body> </html> |
The output of the code above will
be:
My name is Kai Jim Refsnes. My name is Hege Refsnes. My name is Stale Refsnes. |
The following function has two
parameters:
<html> <body> <?php function writeMyName($fname,$punctuation) { echo $fname . " Refsnes" . $punctuation . "<br />"; } echo "My name is "; writeMyName("Kai Jim","."); echo "My name is "; writeMyName("Hege","!"); echo "My name is "; writeMyName("Ståle","..."); ?> </body> </html> |
The output of the code above will
be:
My name is Kai Jim Refsnes. My name is Hege Refsnes! My name is Ståle Refsnes... |
Functions can also be used to
return values.
<html> <body> <?php function add($x,$y) { $total = $x + $y; return $total; } echo "1 + 16 = " . add(1,16) ?> </body> </html> |
The output of the code above will
be:
1 + 16 = 17 |