PHP Functions

The 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 in this article.

The purpose of PHP functions:

  • Functions make code as organized by keeping separate places for each operation.
  • If the same set of code need to be executed again and again, repetition in the 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 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 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, an error will occur on execution.

php_functions

PHP functions – Example

The following example will show how to create a 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, a 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 a result which is printed to the browser. Here, the 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