PHP Functions

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;
     }
 ?> 

Function taking an array as a parameter

<?php
     function takes_array($input)
     {
         echo "$input[0] + $input[1] = ", $input[0]+$input[1];
     }
?> 

 


Function passing arguments by reference

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.'
?> 

 


Functions with parameters with default values

The following shows how to define a function with arguments with default values:

<?php
function doit($type = "txt")
{
    return "Default type is $type.\n";
}
echo doit();
echo doit(null);
echo doit("jpg");
?>

Built-in Functions

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.

© Lynne Grewe