Home    Articles

 

How to create a function in php

 

The functions are cod sequences that can be used several times.
The called function will have same number of params as the declaration of the function.

How to declare the function with two params(arguments):

<?php
function foo($val1, $val2 = 0)
{
  return $val1+$val2;
}
?>

How to call the function:

<?php
function foo($val1, $val2 = 0)
{
  return $val1+$val2;
}
 
echo foo(1); //ex: 1) the function will return 1
echo foo(1,2); //ex: 2) the function will return 3
?>

As this example shows, the first argument is mandatory in both cases.
The second argument will take the 0 value if in the call of the function the second argument is missing. If the second argument is there $val2 will not take 0 as its value.

It is recomanded to have the arguments with some default values in order to encrease the security of your code.

This is one simple example where you add two values, but you can do much more.
Enjoy

by