Functions are defined simply in PHP with the keyword funciton. There is no return type for a function and parameters are defined without type. Below are a few examples showing you how to create your own functions.
In the first generic example, you see a function (myFunction) defined with n arguments and the last line of code returns a value. You would simply call this function via:
$the_value = myFunction($a1,$a2,...$an);
<?php function myFunction($arg_1, $arg_2, /* ..., */ $arg_n) { echo "Example function.\n"; return $retval; } ?>
<?php function takes_array($input) { echo "$input[0] + $input[1] = ", $input[0]+$input[1]; } ?>
by default arguments are passed by value to a function. The following code illustrates how to pass by reference:
<?php function add_some_extra(&$string) { $string .= 'and something extra.'; } $str = 'This is a string, '; add_some_extra($str); echo $str; // outputs 'This is a string, and something extra.' ?>
The following shows how to define a function with arguments with default values:
There are many built-in functions in PHP. They will be introduced in our examples and in topical discussions. See php.net for more details and to search for functions.
While some built-in functions are standard in PHP, some require PHP server to be compiled with special packages. For example, to use image functions such as imagecreatetruecolor(), PHP must be compiled with GD support. Or, to use mysql_connect(), PHP must be compiled with MySQL support.
IMPORTANT: A call to phpinfo() or get_loaded_extensions() will show which extensions are loaded into PHP.