Function in PHP

A Function in PHP is a reusable piece or block of code that performs a specific action. It takes input from the user in the form of parameters, performs certain actions, and gives the output.

Functions can either return values when called or can simply perform an operation without returning any value.

You already have seen many functions like fopen() and fread() etc. They are built-in functions but PHP gives you option to create your own functions as well.

There are two parts which should be clear to you

  • Creating a PHP Function
  • Calling a PHP Function

In fact you hardly need to create your own PHP function because there are already more than 1000 of built-in library functions created for different area and you just need to call them according to your requirement.

Why use Functions?

Better code organization – PHP functions allow us to group blocks of related code that perform a specific task together.

Reusability – once defined, a function can be called by a number of scripts in our PHP files. This saves us time of reinventing the wheel when we want to perform some routine tasks such as connecting to the database

Easy maintenance- updates to the system only need to be made in one place.


Creating PHP Function

Its very easy to create your own PHP function. Suppose you want to create a PHP function which will simply write a simple message on your browser when you will call it.

Following example creates a function called writeMessage() and then calls it just after creating it.

Note that while creating a function its name should start with keyword function and all the PHP code should be put inside { and } braces as shown in the following example below.

<?php
	// Defining a PHP Function
	function writeMessage(){
		echo "You are really a nice person.";
	}
?>

Calling PHP Function

A function call consists of the function name followed by parentheses. If you want to pass information to the function, you place it between these parentheses. A piece of information passed to a function in this way is called an argument.

strtoupper("Hello Web!");

This example calls the strtoupper() function, passing it the string “Hello Web!”. The function then goes about its business of changing the contents of the string to uppercase letters.

Some functions require that more than one argument be passed to them, separated by commas.

some_function($an_argument, $another_argument);

Most functions return some information back after they’ve completed their task; they usually at least tell whether their mission was successful.

strtoupper() returns a string value, so its usage requires the presence of a variable to accept the new string, such as the following.

$newString = strtoupper("Hello Web!");

You may now use $new_string in your code, such as to print it to the screen.

echo $newString;

This code results in the following text on the screen: HELLO WEB!


PHP Functions with Parameters

PHP gives you option to pass your parameters inside a function. You can pass as many as parameters your like. These parameters work like variables inside your function.

Following example takes two integer parameters and add them together and then print them.

<?php
	// Defining a PHP Function with parameters
	function addTwoNumber($numOne, $numTwo){
		$sum = $numOne + $numTwo;
		echo "Sum of two number is: $sum";
	}
	addTwoNumber(10, 20);
?>

Function with an Optional Parameter

When the fontWrap() function is called with a second argument, as in line 6, this value is used to set the font-size attribute of the span element. When this argument is omitted, as in lines 7, 8, and 9, the default value of “12pt” is used instead.

You can create as many optional arguments as you want, but when you’ve given an argument a default value, all subsequent arguments should also be given defaults.

<?php
	function fontWrap($txt, $fontsize = “12pt”)
	{
		echo “<span style=\”font-size:$fontsize\”>”.$txt.”</span>”;
	}
	fontWrap(“A Heading<br/>”,”24pt”);
	fontWrap(“some body text<br/>”);
	fontWrap(“smaller body text<br/>”);
	fontWrap(“even smaller body text<br/>”);
?>

Passing Arguments by Reference

When you pass arguments to functions, they are stored as copies in parameter variables. Any changes made to these variables in the body of the function are local to that function and are not reflected beyond it, as illustrated in below example.

<?php
	function addFive($num)
	{
		$num += 5;
	}
	$orignum = 10;
	addFive($orignum);
	echo $orignum;
?> 

When you access this script through your web browser, it produces the following: 10 A copy of the contents of $orignum is stored in the variable $num. Although $num is incremented by 5, this has no effect on the value of $orignum.

When $orignum is printed, you find that its value is still 10. You can change this behavior by creating a reference to your original variable. You can think of a reference as a signpost that points to a variable.

Using a Function Definition to Pass an Argument to a Function by Reference

When you pass an argument to a function by reference, as in line 7, the contents of the variable you pass ($orignum) are accessed by the argument variable and manipulated within the function, rather than just a copy of the variable’s value (10).

Any changes made to an argument in these cases change the value of the original variable.

<?php
	function addFive(&$num)
	{
		$num += 5;
	}
	$orignum = 10;
	addFive($orignum);
	echo $orignum;
?> 

When you access this script through your web browser, it produces the 15.


PHP Functions Returning Value

A function can return a value using the return statement in conjunction with a value or object. return stops the execution of the function and sends the value back to the calling code.

You can return more than one value from a function using return array(1,2,3,4).

Following example takes two integer parameters and add them together and then returns their sum to the calling program.

Note: that return keyword is used to return a value from a function.

<?php
	// returnValue from a PHP Function
	function addTwoNumber($numOne, $numTwo){
		$sum = $numOne + $numTwo;
		return $sum;
	}
	$returnValue = addTwoNumber(10, 20);
	echo "Return value from the function is: $returnValue";
?>

Type of functions in PHP

Functions come in two flavours: those built in to the language and those you define yourself called user defined functions. PHP has hundreds of built-in functions.

  1. Built in Functions
    1. String functions
    2. Numerical functions
    3. Arrays functions
    4. Files functions
    5. Database functions
  2. User Defined Functions

Built in Functions

Built in functions are predefined functions in PHP that exist in the installation package. These PHP inbuilt functions are what make PHP a very efficient and productive scripting language.

The built in functions of PHP can be classified into many categories. Below is the list of the categories.

String Functions

These are functions that manipulate string data.

Numeric Functions

Numeric functions in PHP are the functions that return numeric results. Numeric PHP function can be used to format numbers, return constants, perform mathematical computations etc.

Date Function

The date function is used to format date and time to human readable format.