PHP Functions

Function makes PHP program well understood by separating the code into structured blocks based on the logic and steps involved to execute them. It has some essential purposes, features to be discussed with this article.

Purpose of PHP functions:

  • Functions makes code as organized by keeping separate places for each operations.
  • If same set of code need to be executed again and again, repetition in code will be avoided by using functions.
  • Each function expected to receive data as input, process them, and then to return output or simply print the manipulated data.

Features of function

  • PHP functions can be either of user defined or predefined.
  • Functions can receive data as an argument will be come under its local scope. It can also receive data in global scope using global keyword or $GLOBALS[] array of PHP as we have discussed about variable scope in PHP.
  • PHP in-built functions are sometimes called as language constructs like echo() or print().

Cautions:

  • Added to the naming conventions to be followed for variable declaration, functions should not start with __ character. Because, functions start with __ characters are considered as magic methods like __clone() as we have seen in PHP Cloning article.
  • Functions that have return type must return any value. Otherwise, error will occur on execution.

php_functions

PHP functions – Example

The following example will show how to create an user defined function in PHP that return the required value.

<?php
$numbersCount = 5;
$total = calculateTotal($numbersCount);
echo $total;
function calculateTotal($n) {
$result = ($n*($n+1))/2;
return $result;
}
?>

The above program is used to calculate the total of first five consecutive integers. First, total number of integers to be added is initialized to the $numberCount variable. And then, calculateTotal() method is called by passing the $numberCount as an argument. The function will return the total as result which is printed to the browser. Here, output of the program is 15 that will be returned to the browser.

This PHP code tutorial was published on April 19, 2013.

↑ Back to Top