PHP Functions

PHP Function is a special block of code that we can write and will be executed whenever we need it. Using PHP functions we can write a code which is more readable.

So basically we can say that a function behaves like a little program, that we can use to reuse code and write less in our programs, for instance, imagine a calculator program, in which the user can make a lot of additions, this would require to use code for making this additions as many times as the user needs, and with a simple function we can reuse the same code. Lets see how we can create these functions.

There are two PHP function types: User Defined and Built in. PHP has more than 700 built-in functions in PHP that can be used to write PHP script.

Need of functions in PHP

The prime goal of any programming language is to automate any task no matter how much trivial or big that task is. With the help of a programming language, you can easily automate task ranging from routine work to your business needs. However, as these tasks grow increasingly complex, you’ll often wind up doing extra work because of doing repetitive tasks e.g. writing a code for validating an e-mail id as a separate function and then using it in different applications would be considered a great practice rather than writing the same code over and over again every time you need it.

PHP User Defined Functions

Besides the built-in PHP functions, we can create our own functions.

  • A function is a block of statements that can be used repeatedly in a program.
  • A function will not execute immediately when a page loads.
  • A function will be executed by a call to the function.
  • A function may be defined using syntax such as the following:

Pseudo code to demonstrate function uses:

Let’s take a look at the generic structure of a function, and then we’ll discuss some of the in’s and out’s of passing information to a function, and getting information back out.

Example:

<?php
function foo($arg_1, $arg_2, /* ..., */ $arg_n)
{
echo "Example function.\n";
return $retval;
}
?> 

One of the greatest benefits of a function is that once you’ve written one and got it working, there is no reason for you to have to write it again. Instead, you call the function from another location(s) in your code, as often as you like, with the only prerequisite being that the function must be declared before it is called.

Another argument is, Functions need not to be defined before they are referenced, except when a function is conditionally defined. When a function is defined in a conditional manner, its definition must be processed prior to being called.

Function names follow the same rules as those governing regular variable names. You can’t start them with a number (although they can contain numbers), you can’t use periods (“.”)or other syntactical punctuation, with the single exception of the underscore (“_”), you can’t use spaces, and you can’t use reserved words. Other than that, the world is your oyster, so make the names descriptive and simple. Again, as with variables, make sure that you pick a naming style and stick to it.

Creating a Function in PHP

At the time you are creating a PHP function, follow these simple guidelines:

  • Always begin your function with the keyword function.
  • Remember that your function’s code must be between the “{” and the “}”.
  • At the time you are utilizing your function, make sure you spell the function name correctly.

When we create a function, we first need to give it a name, like my_function.

Example on creating a function in PHP:

If you want a function to just perform an action without any inputs then you would follow the example shown below, where the argument list is empty.

<?php 
// This function will not execute until call it 
function my_function () 
{      
 echo "Hello World!";      
} 
// Make the function run here by calling it 
my_function (); 
?> 

This type of function is best used for performing a set task. An example application would be output the current date. Below example shows a sample page where the current date is output in a table by calling the custom print_date() function.

<?php

function print_date() {
// get formatted date
$date = date("d M Y");
// output
echo '<table align=center border=1>
<tr><td>' . $date . '</td></tr>
</table>';
}

// output headers
echo '<html><body>';

// print date table
print_date();

// output footers
echo '</body></html>';

?> 

So that’s how you have a function perform a simple task. But what about having it deal with some inputs (arguments)? Well, using the basic format for a function, you can have as many arguments as you need separated by commas.

Guidelines: There are a couple of points which you should remember while naming your functions.

  • Your function’s name should reflect what your function does e.g. naming a function as add_numbers() rather than some random name like xyz_abc() would clearly indicate that this function will add numbers.

  • Your function name must start with either a character (a-z or A-Z) or an underscore (_). It must not contain any number at the beginning of name. However, the rest of the function name can be a combination of numbers, characters and underscore.

What is Variable Scope in a Function

At this point I should mention variable scope. If you don’t know what this is, then I would recommend you check out a beginner tutorial on variables. Essentially, if you have a variable with global scope, and define another variable locally with the same name, then it will be treated as a different variable. The variable referred to in the function will only affect the local version. If you haven’t defined a new variable, however, you can access variables of global scope. Any changes are made to those variables will be reflected in the global variables. Check out figure 1.4 for an example of this.

 <?php
// function with repeated variable name
function monkey ($name) {
echo $name;
}

$name = 'Fred';
monkey ('Pineapple');
echo $name;
?> 

Essentially, you have defined the global variable $name as ‘Fred’, but you have an argument called $name inside the function monkey(), which declares a local version of $name. If you were to run the script then you would see the word ‘PineappleFred‘ appear on the screen, because the local version of $name gets output first, and is set to ‘Pineapple’ in the call monkey (‘Pineapple’);. You’ll notice, however, that the global version of $name isn’t altered, so the echo() afterwards prints out ‘Fred’. If, however, you changed the argument in monkey() to $monkey_name, then you would see ‘FredFred‘ output.

So now we have the ability to use a function to perform an action, and how to feed a function information, but how do we get a function to return a variable? Quite simple, in fact; we use the language construct return.

PHP Functions Arguments or Parameters

We pass arguments to PHP functions in order to process variable data and display, store, or return results.

Although, functions that don’t take parameters might be enough for trivial as well as some big tasks but the kind of dynamism and flexibility that functions that have parameters can offer is really great. Perhaps, that must be the reason why PHP offers so much variety and flexibility when it comes to create functions with parameters. In this section, we’ll learn about how to create functions with parameters and how to invoke such functions.

You define parameters inside parenthesis in functions, see the example below:

Example on Passing one argument to function:

<?php

/*Notice in this function 2 different parameters separated by the ',' character, they will be variables and may affect the result of the function*/
function add_Numbers($number_a,$number_b)
{
   $result = $number_a+$number_b; /*We make the addition and store the result in a new variable*/
   echo $result; /*we print the result on our document */
}

/*Now lets call this function...twice*/

add_Numbers(10,5);
add_Numbers(7,-11);

?>

Example on Passing more than one argument to PHP functions:

<?php 
// This function will not execute until call it 
function my_function ($var1, $var2) 
{ 
 echo  $var1 . $var2; 
} 
// Send the function 2 arguments and fire the function off 
my_function ("PHP ", "is a scripting language."); 
?> 

The Output will be:

PHP is a scripting language.

The syntax for creating a function with parameters is same as the one we’ve used for creating a normal function. Here, all you  have to do is just specify the parameter(s) (if more than one, use comma to separate each parameter) you want your function to have while defining a function.

Returning Values from PHP functions

Many times we will want our custom PHP function to return a value to your script rather than displaying the data when the function runs.

Using the PHP return statement we can accomplish this easily. The return statement will stop the function from running any further, and send a return value back to the code that called the function to run.

However, PHP function can only return one value, although that value can be any integer, float, array, string, etc. that we choose!
To capture this value we can set a variable equal to the PHP function.

Example on Returning value from function in PHP:

<?php 
function mySum($numX, $numY)
{ 
 $total = $numX + $numY; 
 return $total; 
} 
$myNumber = 0; 
echo "Before the function, myNumber = ". $myNumber ."<br />"; 
$myNumber = mySum(3, 4);  // Store the result of mySum in $myNumber 
echo "After the function, myNumber = " . $myNumber ."<br />"; 
?> 

Output will be:

Before the function, myNumber = 0
After the function, myNumber = 7

Different Ways of passing values to the arguments in PHP

Like I said before, PHP offers a great  deal of flexibility and choice when it comes to passing values to the arguments. Here are listed the ways to do so

  • Passing arguments by value
  • Passing arguments by reference
  • Default argument values

So, lets take a quick peek into this.

Passing Arguments by Value

This is the most common way of passing argument value (just like we did in the above example) in which you simply pass a value which may be an integer/float or a string/character or even an array depending on your function’s need.

Take a look at an example of passing arguments by value in PHP

Continuing with above example, lets pass the values in our add_numbers() function. Here are the two ways in which you can call this function by passing values in arguments.

The first way is same as what we did before.

<?php
add_numbers(16, 22);
?>

Also, you’re not bound to pass only static values to the functions, you can also pass variables. Take a look at this

<?php

$val1 = 16;

$val2 = 22;

add_numbers($val1, $val2);

?>

Both ways will generate the same output

The sum of 16 and 22 is 38

When you pass an argument in this manner, it’s called passing by value. This means that any changes made to those values within the scope of the function are ignored outside of the function. If you want these changes to be reflected outside of the function’s scope, you can pass the argument by reference.

Passing Arguments by Reference

At times, you may want any changes made to an argument within a function to be reflected outside of the function’s scope. Passing the argument by reference accomplishes this. Passing an argument by reference is done by appending an ampersand to the front of the argument.

Take a look at an example of passing arguments by reference in PHP

Lets create another variation of our add_numbers() function to understand this concept.

<?php
function add_numbers_ref($num1$num2, &$sum){
$sum  $num1 $num2;
echo 'The sum of ' $num1 ' and ' $num2 ' is ' $sum;
}
?>

Now, lets call this function

<?php
$sum 0;
$val1 16;
$val2 22;
add_numbers_ref($val1$val2$sum);
echo "<br/>Value 1: $val1 <br/> Value 2: $val2 <br/> Sum: $sum";
?>

The above code will generate the following output

The sum of 16 and 22 is 38
Value 1: 16
Value 2: 22
Sum: 38

Explanation of example of passing arguments by reference in PHP

Here, add_numbers_ref() is a function which takes three arguments. First two arguments i.e. numbers to add are passed by values while the third argument $sum is passed by reference (notice the ampersand & before $sum in the function definition). The rest of the code is very straightforward.

Default Argument Values

Default values can be assigned to input arguments, which will be automatically assigned to the argument if no other value is provided. This has an advantage – if no or less arguments  are provided for a function and a default value is specified for the missing arguments no error will be thrown due to missing parameters.

Lets take a look at an example of how default argument values work in PHP

Lets modify our add_number() function to work with default values. Here we’re  providing default values of 5 and 10 in case when no numbers are provided for addition.

<?php
function add_numbers($num1 5$num2 10){
$sum  $num1 $num2;
echo 'The sum of ' $num1 ' and ' $num2 ' is ' $sum '<br/>';
}
add_numbers();                            //No values are passed.
add_numbers(12);                       //Value of first argument is passed.
add_numbers(12, 16);                //Values of both arguments are passed.
?>

The following output will be generated

The sum of 5 and 10 is 15
The sum of 12 and 10 is 22
The sum of 12 and 16 is 28

Explanation of above output

In the function definition of function  add_numbers() default values 5 for first argument and 10 for second are set. Now, here we are calling the function three times and in three different ways.

  • First without any arguments (add_numbers()). In this case, default values for both arguments i.e. 5 and 10 are taken and function acts upon these values. Hence, the output says The sum of 5 and 10 is 15 in the first line of output.
  • In second case, first argument is specified but second argument is left void (add_numbers(12)). In this case, specified value for first argument i.e. 12 and default value for second argument i.e. 10 are taken and function acts upon these values. Hence, the output says The sum of 12 and 10 is 22 in the second line of output.
  • In the third case, values for both arguments are specified (add_numbers(12, 16)). In this case, specified value for both arguments i.e. 12 and 16 are taken and function acts upon these values. Hence, the output says The sum of 12 and 16 is 28 in the third line of output.

Difference between passing arguments by value and passing arguments by reference

Well if you still don’t understand the difference between passing arguments by value and reference don’t blame yourself. This topic is a bit tricky. But don’t worry we have a simple yet a very good example to clear things up for you. So here it is

Here is a simple code for swapping two numbers.The following code has two functions swap_val() (for passing as value) and swap_ref() (for passing as reference). Both functions take two arguments.

<?php

$val1 = 12;

$val2 = 15;

function swap_val($num1, $num2){

$temp = $num1;

$num1 = $num2;

$num2 = $temp;

echo “<p>Swapped No 1: $num1<p/>”;

echo “<p>Swapped No 2: $num2<p/>”;

}

function swap_ref(&$num1, &$num2){

$temp = $num1;

$num1 = $num2;

$num2 = $temp;

echo “<p>Swapped No 1 : $num1<p/>”;

echo “<p>Swapped No 2: $num2<p/>”;

}

swap_val($val1, $val2);

echo “<p>Original Value 1: $val1<p/>”;

echo “<p>Original Value 2: $val2<p/>”;

swap_ref($val1, $val2);

echo “<p>Original Value 1: $val1<p/>”;

echo “<p>Original Value 2: $val2<p/>”;

?>

The output of this code is

Swapped No 1: 15
Swapped No 2: 12
Original Value 1: 12
Original Value 2: 15
Swapped No 1 : 15
Swapped No 2: 12
Original Value 1: 15
Original Value 2: 12

Explanation of output

Lets understand what happened

  • First the function swap_val() is called by swap_val($val1, $val2) with $val1=12 (as $num1) and $val2=15 (as $num2) .
  • Then, inside the swap_val() function, swapping is done and swapped values are printed on the screen resulting into first two lines of the output.
  • Now outside the swap_val() function are the two echo statements printing values of $val1 and $val2 respectively. Here if you notice properly you will see that the values of both $val1 and $val2 are restored to their original values (output line no 3 and 4). This tells us that even though we have swapped the values of variables it caused no effect whatsoever on the original variable values i.e. any changes made to those values within the scope of the function swap_val() are ignored outside of the function swap_val(). This happens in case of passing arguments by value.
  • Now moving forward, after those two echo statements there is a function call to the function swap_ref(), again with the same values $val1=12 (as $num1) and $val2=15 (as $num2) . But this time both values are passed by reference (notice the ampersand before the arguments in the swap_ref() function definition). Again, inside swap_ref() swapping is done and swapped values are again echoed. Check output line 5, 6.
  • Now the main part, after the call to the function swap_ref() are two echo statements which are again printing the values of $val1 and $val2. But if you notice the output (last two lines of the output) you’ll see that now the original values of  $val1 and $val2 are swapped i.e. now value of $val1 is 15 instead of 12 and $val2 has value 12 instead of 15. This happens when you pass arguments by reference. In other words, changes are actually made on the actual argument and are retained outside the function’s scope.

That’s the difference between passing arguments by value and passing arguments by reference. Lets hope this example helped you in understanding this topic and difference between them a bit clearly (If you still have doubts feel free to comment and ask).

Functions which return variables

Let’s take a look at a useful example of this. Following is the code for a function which processes a string variable, striping slashes, trimming excess white space at both ends, and then returns it.

<?php
// Declare cleaning function
function clean_it ($string_variable) {
$string_variable = trim(stripslashes($string_var));
return $string_variable;
}

// Clean up form data
$name = clean_it ($_POST['user_name']);
$pwd = clean_it ($_POST['user_password']);

// Use data...
?> 

If you pay attention to the fact that the information provided from the $_POST[] variables are from a form then you will begin to understand the usefulness of this function. It doesn’t do anything that you couldn’t achieve anyway, but it does reduce your typing, and means that you also reduce the chance of making an error. The variable $name now contains a cleaned version of $_POST[‘user_name’], while $pwd contains a clean version of $_POST[‘user_password’]. This example is a small simplification of your code, but when you have to nest large numbers of functions and calls, particularly with complicated code, it really makes a difference.

There is a risk, at times, of people going overboard and trying to turn everything into a function… Don’t. Sometimes you are better off keeping your code together. As a general rule, however, if you find that you are repeating segments of code again and again, then throw it into a function. The same applies for chunks of code that you use in almost all of your scripts – make it a function. You can even store your most commonly used functions in an extra file and then call it using the include() function. The idea here is that you build up a library of working, useful functions which then speed up your development time. Another advantage is that if you fix it once, it’s fixed for all the files which use it, rather than having to go through five or fifty different pages fixing the same problems over and over again.

Conditional functions

Example

<?php

$makefoo = true;

/* We can't call foo() from here
since it doesn't exist yet,
but we can call bar() */

bar();

if ($makefoo) {
function foo()
{
echo "I don't exist until program execution reaches me.\n";
}
}

/* Now we can safely call foo()
since $makefoo evaluated to true */

if ($makefoo) foo();

function bar()
{
echo "I exist immediately upon program start.\n";
}

?> 

Functions within functions

Example

<?php
function foo()
{
function bar()
{
echo "I don't exist until foo() is called.\n";
}
}

/* We can't call bar() yet
since it doesn't exist. */

foo();

/* Now we can call bar(),
foo()'s processing has
made it accessible. */

bar();

?> 

All functions and classes in PHP have the global scope – they can be called outside a function even if they were defined inside and vice versa.

PHP does not support function overloading, nor is it possible to undefine or redefine previously-declared functions.

Recursive functions

Recursive functions, or functions that call themselves, offer considerable practical value to the programmer and are used to divide an otherwise complex problem into a simple case, reiterating that case until the problem is resolved.

Example

<?php
function recursion($a)
{
if ($a < 30) {
echo "$a\n";
recursion($a + 1);
}
}
?>  

Note:

Recursive function/method calls with over 100-200 recursion levels can smash the stack and cause a termination of the current script. Especially, infinite recursion is considered a programming error.

Lets take a look at another example of simple factorial problem using recursion

<?php

function get_factorial($num) {

if($num == 0 || $num == 1)

return 1;

else

$factorial = get_factorial($num-1)*$num;

return $factorial;

}

echo “Factorial of $val = ” . get_factorial($val);

?>

The following output will be generated

Factorial of 4 = 24

Explanation of factorial program using recursion

Lets take a look at how recursion process works. In the above program we have a function get_factorial() which is calculating the factorial of a number passed as a parameter to the function by recursively calling itself. For the sake of example we’ll learn how the process works by calculating factorial of 4. Here are the steps involved.

  • Inside the function is an if-else condition. In the if part we’re checking if the number (whose factorial is being calculated) becomes 0 or 1 and if it does become equal to any one of them we’re returning 1 (factorial of both 0 and 1 is 1) and that’s when we stop the recursion. Otherwise, we’re calling the function recursively until the process stops.
  • In else part, we’re calculating the factorial by the expression –                                                    $factorial = get_factorial($num-1)*$num. Now lets understand what happens here.
  • First thing you should probably know about function calls is that whenever you call a function your processor marks a position for that function on top of a stack. Your function will continue to stay in that stack until it finishes  its execution. Hope you get this part because the rest of the explanation depends on this part.
  1. Now back to our example (I recommend you to keep a pen and paper with you and write the bold part below for proper understanding), when the function is first called with an argument value of 4 i.e. get_factorial(4). This is stored or pushed onto the stack. Inside the function, the if condition becomes false and inside else the  function is recursively called by get_factorial(4-1)*4. Now a function call to get_factorial(4-1)*4 is made and it is also pushed on top of the stack. Remember get_factorial(4) is still inside that stack but now below get_factorial(4-1)*4 function call.
  2. Now the program will again call the get_factorial function but this time with a value of 4-1 or 3. Again the if condition becomes false and in else  the  function is recursively called by get_factorial(3-1)*3.
  3. Now the program will again call the get_factorial function but this time with a value of 3-1 or 2. Again the if condition becomes false and in else  the  function is recursively called by get_factorial(2-1)*2.
  4. Now the program will again call the get_factorial function but this time with a value of 2-1 or 1. This time the if condition becomes true and it returns 1.

The current stack positions are

  • 1 is returned

  • get_factorial(2-1) = 1 (just returned)

  • get_factorial(3-1) = get_factorial(2-1)*2

  • get_factorial(4-1) = get_factorial(3-1)*3

  • get_factorial(4) = get_factorial(4-1)*4

Just remember the above stack positions. Now lets see how the stack is cleared and final output is obtained.

  1. In the fourth step above, call to get_factorial(2-1) returned 1. This will cause the program to remove the value from the top of the stack and finish its calculation. So it will pop out the get_factorial(2-1) function call and return 1 for it.
  2. Now function call to get_factorial(3-1)  is on the top of the stack and its value is equal to get_factorial(2-1)*2. Since the call to the function get_factorial(2-1) has returned, the value of get_factorial(3-1) can be also calculated as get_factorial(2-1)*2 or 1*2 = 2.
  3. Now function call to get_factorial(4-1)  is on the top of the stack and its value is equal to get_factorial(3-1)*3. Since the call to the function get_factorial(3-1) has returned, the value of get_factorial(4-1) can be also calculated as get_factorial(3-1)*3 or 2*3 = 6.
  4. Now function call to get_factorial(4)  i.e. our original function call is on the top of the stack and its value is equal to get_factorial(4-1)*4. Since the call to the function get_factorial(4-1) has returned, the value of get_factorial(4) can be also calculated as get_factorial(4-1)*4 or 6*4 = 24. And that’s our final output.
  5. Since there is no other pending function calls in the stack so the program will continue to work from the line just after the original function call.

Hope, the explanation wasn’t too mush confusing. It would be better if you try to solve other problems by yourself. And for further queries feel free to comment and ask.

PHP Built-In Functions

Like other programming language, PHP offers some built-in functions for day-to-day use in our coding. Most of these functions are very helpful in achieving programming goals and are well documented.

Conclusion:

So what have we learned? We now know that a function is a block of code which can be called from any point in a script after it has been declared. Functions are useful because they contribute to rapid, reliable, error-reducing coding, and increase legibility by tiding up complicated code sequences.

Functions may be used to perform actions, accept variables, change variables, and return variables. Storing many functions in an external file and referencing it with the include() function is a way to build up a library of functions, further enhancing your productivity.

Add a Comment

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

ABOUT CODINGACE

My name is Nohman Habib and I am a web developer with over 10 years of experience, programming in Joomla, Wordpress, WHMCS, vTiger and Hybrid Apps. My plan to start codingace.com is to share my experience and expertise with others. Here my basic area of focus is to post tutorials primarily on Joomla development, HTML5, CSS3 and PHP.

Nohman Habib

CEO: codingace.com

Request a Quote