Child

PHP: Functions


A function is a block of code which can be called from any point in a script after it has been declared. It is basically a compartmentalized PHP script designed to accomplish a single task. Furthermore, code contained within functions is ignored until the function is called from another part in the script. Functions are useful because they contribute to rapid, reliable, error-reducing coding, and increase legibility by tiding up complicated code sequences.

It is good programming practice to use functions to modularize your code and to better provide reuse. To declare a function, you simply type:

<?php 
   function function_name(param_1, ... , param_n) 
   { 
      statement_1; 
      statement_2; 
      ...
      statement_m; 

      return return_value; 
   } 
?>

PHP function guidelines:

  • Give the function a name that reflects what the function does
  • The function name can start with a letter or underscore (not a number)

Example

A simple function that writes my name when it is called:

<html>
<body>

<?php
function writeName()
{
echo "Mamun Hossain Onick";
}

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

</body>
</html>

Output:

My name is Mamun Hossain Onick

PHP Functions - Adding parameters

To add more functionality to a function, we can add parameters. A parameter is just like a variable.

Parameters are specified after the function name, inside the parentheses.

Example 1

The following example will write different first names, but equal last name:

<html>
<body>

<?php
function writeName($fname)
{
echo $fname . " Chowdhury.<br>";
}

echo "My name is ";
writeName("Mamun Hossain Onick");
echo "My sister's name is ";
writeName("Ruby");
echo "My brother's name is ";
writeName("Manik");
?>

</body>
</html>

Output:

My name is Mamun Hossain Onick Chowdhury.
My sister's name is Ruby Chowdhury.
My brother's name is Manik Chowdhury.

Example 2

The following function has two parameters:

<html>
<body>

<?php
function writeName($fname,$punctuation)
{
echo $fname . "Chowdhury" . $punctuation . "<br>";
}

echo "My name is ";
writeName("Mamun Hossain Onick",".");
echo "My sister's name is ";
writeName("Ruby","!");
echo "My brother's name is ";
writeName("Manik","?");
?>

</body>
</html>

Output:

My name is Mamun Hossain Onick Chowdhury.
My sister's name is Ruby Chowdhury!
My brother's name is Manik Chowdhury?

PHP Functions - Return values

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

Example

<html>
<body>

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

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

</body>
</html>

Output:

1 + 16 = 17