The real power of PHP comes from its functions.
In PHP, more than 1000 built-in functions are provided.
For a complete reference manual and examples of all array functions, visit our PHP Reference Manual.
In this chapter, we'll show you how to create your own functions.
To execute a script when the page loads, you can put it inside a function.
Functions are executed by calling functions.
You can call functions anywhere on the page.
Functions are executed by calling functions.
<?php function functionName ( ) { // Code to be executed } ?>
PHP function guidelines:
The name of the function should suggest what it does
Function name starts with a letter or underscore (cannot start with a number)
A simple function that prints my name when called:
<? php function writeName (){ echo " Kai Jim Refsnes " ;} echo " My name is " ; writeName (); ?>
Output:
My name is Kai Jim Refsnes
To add more functionality to a function, we can add parameters. Parameters are like variables.
Parameters are specified within parentheses just after the function name.
The following example will output different first names, but the same last name:
<? php function writeName ($ fname ){ echo $ fname . " Refsnes.<br> " ;} echo " My name is " ; writeName ( " Kai Jim " ); echo " My sister's name is " ; writeName ( " Hege " ); echo " My brother's name is " ; writeName ( " Stale " ); ?>
Output:
My name is Kai Jim Refsnes.My sister's name is Hege Refsnes.My brother's name is Stale Refsnes.
The following function takes two parameters:
<? php function writeName ($ fname ,$ punctuation ){ echo $ fname . " Refsnes " . $ punctuation . " <br> " ;} echo " My name is " ; writeName ( " Kai Jim " , " . " ); echo " My sister's name is " ; writeName ( " Hege " , " ! " ); echo " My brother's name is " ; writeName ( " Ståle " , " ? " ); ?>
Output:
My name is Kai Jim Refsnes.My sister's name is Hege Refsnes!My brother's name is Ståle Refsnes?
To have a function return a value, use the return statement.
<? php function add ($ x ,$ y ){ $ total =$ x +$ y ; return $ total ;} echo " 1 + 16 = " . add ( 1 , 16 ); ?>
Output:
1 + 16 = 17