User Defined functions

A function’s syntax is :

function function_name($argument1, $argument2……$argumentn)
{
statement1;
statement2;

statementn;
}

A function may be defined using syntax such as the following:

<?php
echo "hello functions";
function1();
echo "after first function";
echo "<br>";
function2(10);

// Function 1
function function1()
{
	echo "simple function without arguemnts";
}

// Function 2
function function2($argument)
{
	echo "this is the passed value " . $argument;
}
?>

Any valid PHP code may appear inside a function, even other functions and class definitions.

Function names follow the same rules as other labels in PHP. A valid function name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thus: [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*.

Recursive functions

It is possible to call recursive functions in PHP. However avoid recursive function/method calls with over 100-200 recursion levels as it can smash the stack and cause a termination of the current script.

<?php
// calling function
recursion(10);


function recursion($a)
{
    if ($a < 20) {
        echo "$a\n";
        recursion($a + 1); // recursive call
    }
}
?>