PHP Tutorials: PHP Functions

In this tutorial, I am going to explain to you about PHP functions. You can call it

  • A function
  • A method
  • A procedure

In the modern object-oriented time we emphasize on the word method. First, we should know, what a function is and why we use it?

What is a function?

A function is a block of code that can be called from any place of the program by its name. A function has the following elements:

  • Function name [required]
  • Parameters [optional]
  • Body [required]
Syntax:
<?php
function functionName( $parm1, $parm2 ){
	# code...
}
?>

Why we use functions?

Nobody likes to write some piece of code again and again which performs a same action. To reduce our efforts we can write that specific code inside a function and call it anywhere with its name. Let us take an example of a function that find out if a number is prime or not.

<?php
	function IsPrime($n) {
	    for($x=2; $x<$n; $x++) {
	      if($n % $x ==0) { return false;}
	    } 
	    return true;
	}

	$num = 13;
	$result = IsPrime($num);
	echo $result ? "$num is a Prime Number.<br>" :  "$num is not a Prime Number.<br>";

	$num = 15;
	$result = IsPrime($num);
	echo $result ? "$num is a Prime Number.<br>" :  "$num is not a Prime Number.<br>";

	$num = 17;
	$result = IsPrime($num);
	echo $result ? "$num is a Prime Number.<br>" :  "$num is not a Prime Number.<br>";

	$num = 19;
	$result = IsPrime($num);
	echo $result ? "$num is a Prime Number.<br>" :  "$num is not a Prime Number.<br>";

	$num = 9;
	$result = IsPrime($num);
	echo $result ? "$num is a Prime Number.<br>" :  "$num is not a Prime Number.<br>";
?>
Lakblog: Prime number
Lakblog: Prime number

Now, imagine if you had to write the prime number code for every single number. Functions make our work easy and our code reusable. Most of the programmers do a mistake while dealing with functions. Let us not repeat that.

Types of functions

There are 2 types of functions.

  1. Predefined or System defined or in-built functions
  2. User defined functions
in-built functions

In-built functions are those functions which are already defined in PHP default libraries. If you remember we read about String functions and Array functions in our previous topics. They called in-built functions. There are lot more in-built functions available in PHP library.

User defined functions

The functions coded by you in your PHP script called an user-defined function. You can defined a function inside a PHP file and call it with its name. The example above of prime number IsPrime() is an user defined function.

Advantages of User-defined functions
  1. Reduces repetition of code in application: As already told the function can be used as many as time you wanted to use it. It can be called by its name whenever you need it.
  2. Easy to maintain: Because you are writing a block of code inside a function, you can manage it very easily. Rather than finding the code in the files you just go to the specific function and modify the code if needed.
  3. Eliminate errors: When you divide the PHP code in functions, it because very easy to eliminate the error or fix the error if any occurs.
  4. Reusable: As explained in the #1 it reduces the code in an application due to it’s reusable feature. Use it whenever you need it.

Defining a function

Here is the syntax of the basic function

<?php
	function FunctionName()
	{
		# code...
	}
?>

The elements of function are explain above. Here is an example of user defined function.

<?php
	function IsPrime($n) {
	    for($x=2; $x<$n; $x++) {
	      if($n % $x ==0) {
	      	echo 'Its not a prime number.';
	      }
	    } 

	    echo 'Its a prime number.';
	    
	}
?>

Function with parameters

Parameter is a value that you pass to a function to perform a specific operation. The parameter can be of any data type. In PHP you can send any number of parameters to a function. For every parameter you can specify a value to perform the action.

Syntax:
<?php
	function FunctionName($value='')
	{
		# code...
	}
?>
Example: 
<?php
	function addNumbers( $num_1, $num_2)
	{	
		$sum = $num_1 + $num_2;
		echo "Sum of $num_1 and $num_2 is $sum<br>";
	}

	addNumbers(10, 15);
	addNumbers(13, 25);
?>
Lakblog: Function with parameters
Lakblog: Function with parameters

Default Value Parameters and Optional Parameters

You can also define default values for parameters. The default values will be used if you do not pass any value with the function call. Here is an example of function with default value parameters.

<?php
	function addNumbers( $num_1 = 15, $num_2 = 10)
	{	
		$sum = $num_1 + $num_2;
		echo "Sum of $num_1 and $num_2 is $sum<br>";
	}

	addNumbers(10);
	addNumbers(13, 25);
	addNumbers();
?>
Lakblog: Function with default parameters
Lakblog: Function with default parameters

Function with return statement or returning a value

As of now we were displaying our results with echo statement inside a function. But it will not be a case every time. From some function we will need an output as a value and then reuse it for further operation. Let us take an example

<?php
	function addNumbers( $num_1 = 15, $num_2 = 10)
	{	
		$sum = $num_1 + $num_2;
		return $sum;
	}

	function divideNumber( $num_1, $num_2 ) {
		$div = $num_1 / $num_2;
		return $div;
	}

	$result = addNumbers(10);
	$div_result = divideNumber( $result, 2 );
	echo "After adding number and diving it with 2 we got: $div_result<br>";

	$result = addNumbers(13, 25);
	$div_result = divideNumber( $result, 2 );
	echo "After adding number and diving it with 2 we got: $div_result<br>";

	$result = addNumbers();
	$div_result = divideNumber( $result, 2 );
	echo "After adding number and diving it with 2 we got: $div_result<br>";
?>
Lalblog: Function return
Lalblog: Function return

In the above example we are adding 2 number and then dividing the result with an another number. So the result returned from the first function addNumbers() is input for another function divideNumber().

Passing Parameters/Arguments by Reference

We just studied passing the arguments to a function, that was quite easy to understand and use. Now, we should know another method of passing the arguments, that is passing arguments by reference. The default method of passing the arguments is by value and that is used widely. When a parameter is passed by value and altered it don’t has any affect outside of the function. However, when an arguments is passed by reference it has affects outside of function as well.

Basically when you pass an argument by reference, you are not actually passing the value of the variable but you are passing the physical memory address of the variable. Read more about variables in my previous topics. When you manipulate the variable you are directly dealing the the memory address and replacing the value there. The ampersand (&) in most of the programming languages refers to physical memory location. Just keep in mind one important thing. When you pass the argument by reference you are playing with the memory location and not the value of the variable itself.

An argument by reference can done by prefixing ampersand (&) with the argument. Here is an example of passing argument by reference.

<?php
function addNumber(&$digit){
    $digit += $digit;
    return $digit;
}

$digit = 5;
echo $digit; // Outputs: 5

addNumber($digit);
echo $digit; // Outputs: 10
?>

Recursive Function

If I explain the recursive function in simple words then it mean a function which keep calling itself until a statement break it or stop it. If you read about loops in my previous topics then this will be very easy for you to understand this topic. Read more about loops before you proceed further. Let us take an example first to understand the recursive function.

<?php
function iAmRecursive( $value='' ) {
	if( $value != 0 ){
		$value += iAmRecursive( ($value - 1) );
	}
	return $value;
}

$argument = 5;
$recursiveResult = iAmRecursive($argument);
echo "Result of $argument recursive is ".$recursiveResult;
?>
Lakblog: Recursive Function
Lakblog: Recursive Function

The function iAmRecursive() taking a value as an argument and keep calling itself until it is 0. Here I am deducting 1 from the $value every time I call the function which keep on going until it is 0. Don’t think that a recursive function will stop calling itself automatically. It is your logic that stops it. Otherwise the function will keep on calling and the program will halt.

Try some examples and share your feedback.

Leave a Reply

Your email address will not be published. Required fields are marked *