Easy Tutorial
❮ Func String Bin2Hex Func Date Localtime ❯

PHP Functions


The true power of PHP comes from its functions.

PHP provides over 1000 built-in functions.


PHP Built-in Functions

For a complete reference manual and examples of all array functions, visit our PHP Reference Manual.


PHP Functions

In this chapter, we will show you how to create your own functions.

To execute a script when the page loads, you can place it inside a function.

Functions are executed by calling the function.

You can call a function at any position on the page.


Creating PHP Functions

Functions are executed by calling the function.

Syntax

<?php
function functionName()
{
    // Code to be executed
}
?>

PHP Function Guidelines:

Example

A simple function that outputs my name when called:

Example

<?php
function writeName()
{
    echo "Kai Jim Refsnes";
}

echo "My name is ";
writeName();
?>

Output:

My name is Kai Jim Refsnes

PHP Functions - Adding Parameters

To add more functionality to a function, you can add parameters, which act like variables.

Parameters are specified within the parentheses after the function name.

Example 1

The following example will output different first names but the same last name:

Example

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

Example 2

The following function has two parameters:

Example

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

PHP Functions - Returning Values

To return a value from a function, use the return statement.

Example

<?php
function add($x, $y)
{
    $total = $x + $y;
    return $total;
}

echo "1 + 16 = " . add(1, 16);
?>

Output:

1 + 16 = 17
❮ Func String Bin2Hex Func Date Localtime ❯